Using Angular DateTime pipe programmatically for hh:mm:ss formats - javascript

I'm trying use DatePipe for HH:MM:SS (or any other documented formats) just as I've used DecimalPipe for monetary values.
However, passing my logic a format such as hh:mm:ss my values immediately turn to 07:00:00.
time = 'hh:mm:ss';
val = '1:02'; // user entered value
invalids = new RegExp('[^0-9:]{0,6}', 'g'); // time chars only
replaced = String(val).replace(invalids, ''); // remove non-hhmmss characters
let value = this.datePipe.transform(replaced, time); // format the value
console.log(value); // '07:00:00' why!?
Here is the repro in StackBlitz:67
How can I get the component to accept those predefined formats to force the input value?

Angular DatePipe's input is typed as any, but actually requires a Date, or miliseconds, or ISO formatted string which you are not giving it.
https://angular.io/api/common/DatePipe#input-value
value any The date expression: a Date object, a number (milliseconds
since UTC epoch), or an ISO string
(https://www.w3.org/TR/NOTE-datetime).
The data you are passing in does not meet that criteria so it's probably not going to work for you use case unless you can modify it before sending to datePipe.

Related

How can I reverse date time to ajax date time

In javascript I have some datetime like this
Date: '2017-07-04'
I want to convert it to DateTime like ajax get result.
Expect result like this:
'/Date(1565089870830)/'
How can I make it possible?
You can use Date.parse(). This method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
var date = Date.parse('2017-07-04');
console.log(date);
The format you're trying to create is a string containing an Epoch timestamp. To create that in JS you can create a Date object from the input string and retrieve the getTime() property. Then it's just a matter of concatenating that value in to the format needed. Try this:
var date = new Date('2017-07-04');
var epoch = date.getTime();
var output = `/Date(${epoch})/`;
console.log(output);
Presumably you're working with an ASP.Net MVC site, given the date format you're trying to build. One thing to note here is that you don't need to use that format when sending DateTime values back to the server. You can send any string so long as it can be bound to a DateTime instance by the ModelBinder. As such I'd recommend using an ISO8601 format instead.

convert iso time strings to valid momentjs format and compare them

I want to compare some times with momentjs. These times come from time pickers and use the ISO 8601 format, 24hr hh:mm (more info here).
I want to compare the examples "01:45" and "13:36". Using the function isSameOrBefore should return me true. Unfortunately
const valid = moment("01:45").isSameOrBefore("13:36")
does not work, because the iso strings use a wrong format. I get the warning
Deprecation warning: value provided is not in a recognized RFC2822 or
ISO format. moment construction falls back to js Date()
I tried to go for this
const isoFormat = 'hh:mm'
const first = "01:45"
const second = "13:36"
const firstBeforeSecond = moment(first, isoFormat).isBefore(second, isoFormat)
console.log(firstBeforeSecond)
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/moment.min.js"></script>
but this still fails. The value I get returned is false and this is not correct. What is the correct way to compare these time strings?
Using moment for this is huge overkill
Just compare strings
"01:45" < "13:36"
is true
"13:36" === "13:36"
is also true
the reason is that in ISO 8601 the strings have the same length and hence will
"00:00" always be the lowest value and "23:59" the highest.
This is safe because they stay string and have ":" in them, so will not be cast to number or lose the leading 0s or such
The correct syntax is:
moment(first, isoFormat).isBefore(moment(second, isoFormat))
try this
var first = moment('01:45', 'hh:mm');
var second = moment('13:36', 'hh:mm');
console.log(first. isSameOrBefore(second));
specifying format will not give any warnings :)

Formating date from milliseconds to this format: DD/MM/YYYY hh:mm:ss (US time locale) using native JS

I need to format this value in milliseconds "1543325996" to date like this "18/01/1970, 11:42:05 PM". I've already got the right result using 'toLocaleTimeString' function, but this result has String type. I need exactly Date type.
function dateFormat(date) {
var formDate = new Date(+date).toLocaleDateString("en-GB");
var formTime = new Date(+date).toLocaleTimeString("en-US");
var concatDate = (formDate + ", " + formTime);
// here I've got error 'Invalid Date'. I know that it's a wrong way, but don't know what to do.
var newDate = new Date(concatDate);
return newDate;
}
but this returns error "Invalid Date". Is there another way to convert String to Date?
...but this result has String type. I need exactly Date type.
Date objects don't have a format. Formatting is intrinsically a textual thing (e.g., string).
If you want Dates, then new Date(+date) is giving you that. There's nothing further required. Later, at some point, if you want to display that date in a textual form, use toLocaleDateString or Intl.DateTimeFormat or similar to format them in the way you want them formatted. But not until/unless you need to convert them to text (a string).

Parse JSON DateTime object to local time in JQuery by ignoring timezone

I am facing an issue while parsing JSON Date Time object using moment(of course I tried many approaches suggested in Stackoverflow but nothing worked in my case).
In my application, I'm storing a DateTime value as UTC DateTime. Now when I'm displaying I need to display it according to the browser timezone. After going through many StackOverflow questions, I used "moment.js" as below
//From server, the Date object looks like /Date(1506510057813)/
//The equivalent DateTime value stored in Database is 2017-09-27 13:00:57.813
fuction DateTimeFormatter(value)
{
if (value != undefined) {
var newValue = new Date(moment.utc(value));
//But at this line, even with just moment(value) all I am getting is DateTime which is not same as UTC time.
//I don't want any time zone to get appended all I want is just 13:00:57
var newHours = newValue.getHours() - newValue.getTimezoneOffset() / 60;
var newMinutes = (newHours + '.0').split('.')[1] * 6;
newValue.setHours(newHours);
newValue.setMinutes(newMinutes);
return moment(newValue).format(applicationTableDateFormat);
}
else
return "";
}
Please let me know what I am doing wrong or is there any other way I can display time as per browser time zone.
Once you have a UTC moment, you can convert it to local.
moment.utc(value).local().format(...)
https://momentjs.com/docs/#/manipulating/local/
But it sounds like maybe your real problem is when you store the date. If you're storing it as UTC, make sure you actually convert the local value to UTC before you store it. That way when you read it, you get a predictable value that you can safely convert to any locale.
Angularjs has its own mechanism to display formatted dates on views you just needs an absolute representation of a date and it takes care of the rest. And by absolute, I mean, a Date which is settled in a timezone whether it's utc or not, you need to know what timezone you are talking about.
The date filter
It's a filter from the core module of angularjs and it accepts:
"... either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone." (Angularjs date filter)
The problem
Angularjs need a proper date input in order to display it correctly, in your case you seem to have the milliseconds format (sort of, /Date(1506510057813)/), you could use that and extract the numeric part and input that on the pipe, or you can change the server to send the ISO 8601 date (a.k.a., yyyy-MM-ddTHH:mm:ss.sssZ).
For example:
let rawDate = '/Date(1506510057813)/';
let re = /\/Date\((\d+)\)\//g; // regex to extract number from the string date
let myDate = new Date(Number(re.exec()[1])) // extract the milliseconds
Or
let rawDate = '2017-09-27T11:00:57.813Z';
let myDate = new Date(rawDate)// and you don't need to do anything else
Either way you'd end up with something like this:
<span> {{ myDate | date }}</span>

Javascript date - Specify incoming date format (jQuery UI DateTimepicker)

I'm using custom plugin for jQuery UI datepicker - Timepicker
I have two fields, from and to input field, and need to check if to "is greater than" from. I have my custom onClose function (onClose: function(dateText, inst) {}), but the first parameter is value of input - a date string. But my date string is not in the "valid" JS datetime format so I'm not able to get Date object instance and compare.
It's dd.mm.yyyy hh:mm, e.g. 06.08.2012 12:00
I wonder if there is anything how to specify input string format, e.g.:
var date = new Date('dd.mm.yyyy hh:mm', dateText);
If not I'll have you parse it somehow...
Thanks for help in advance.
There is no such utility built in to JavaScript. If I were you I would match the date format with a regex and use the form of the Date constructor which accepts date parts:
function parseDate(str) {
var m = str.match(/^(\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d)$/);
return (m) ? new Date(m[3], m[2]-1, m[1], m[4], m[5]) : null;
}
Note that the month part is zero based (instead of one based, so January=0, hence the minux one). Also, note that the Number constructor is used to convert strings to numbers so you don't have to worry about numbers possibly prefixed with a zero being interpreted as octal as can happen with parseInt(...).

Categories