Convert java date into angular date - javascript

I am working on project uses angular4(frontend) and java(backend).
I get the date in below format from java backend server into angular server.
2018-05-23T18:30:00.000+0000
I need to convert it into javascript/angular Date object.
I have tried below code
Date d = new Date(java_date);
but this gives Invalid Date error.
Any idea how to deal with above date format.

The string "2018-05-23T18:30:00.000+0000" is not consistent with the format in ECMA-262, it's missing colon in the timezone offset between the hours and minutes, so implementations may treat it as invalid (e.g. Safari).
You have a number of options:
Replace the timezone offset with "Z" and use the built–in parser: new Date('2018-05-23T18:30:00.000Z')
Insert a colon in the offset and use the built–in parser: new Date('2018-05-23T18:30:00.000+00:00')
Write your own parser for this particular format (maybe 4 lines of code)
Use a library (there are many good ones and they can help with formatting too)
I'd recommend either 3 or 4 as the built–in parser is notoriously fickle, but any of the above will likely do.

The Date as you wrote it - given by its ISO string, you should parse it using JS/Angular
var a = Date.parse("2018-05-23T18:30:00.000+0000");
Here's a relevant link to MDN :
MDN Parse
MDN ISO

Related

Convert date to string in JavaScript

let date="20-05-2022";
const dates=new Date(date);
const out=dates.toString();
console.log(out);
The above snippet output is invalid date.
How to I convert this kind of date format to string.
How to I convert that??.
The JavaScript Date constructor only supports the parsing of strings that meet a simplified version of the ISO 8601 datetime format.
You have a number of options, including:
Rearrange the string to be 'YYYY-MM-DD' before passing it to the Date constructor, or
Parse the year, month and day number values and then pass these into the Date constructor as individual parameters like so: new Date(year, monthIndex, day), or
Use a library like moment.js.
Be careful about timezones: date-only strings (e.g. "1970-01-01") are treated as UTC, while date-time strings (e.g. "1970-01-01T12:00") are treated as local, or, if a timezone offset is supplied (e.g. Z or +02:00), according to that.
And when passing individual numbers for each datetime component to the Date constructor, values are treated as local.
A new, more featureful time API (Temporal) is under development.

How to convert a string into timestamp, with moment js?

I have the string "18/04/19 5:17 PM EDT" which represents a date.
I'm using moment and the add-on moment-timezone and I need to convert this sting into a timestamp.
I'm trying something as:
var date = moment("18/04/19 5:17 PM EDT").format('DD/MM/YY h:m a z');
alert(date);
But this is not working and saying "invalid date".
Please note that moment(String):
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
so you are getting Invalid Date because your input is neither in ISO 8601 nor RFC 2822 recognized format, then you have to provide format parameter when parsing it.
moment(String, String) does not accept 'z' token, so you have to use moment-timezone to parse your input using zone, see Parsing in Zone docs:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
You can use format() and other methods listed in the Displaying section of the docs (e.g. valueOf()) to display the value of a moment object.
Here a live sample:
var date = moment.tz("18/04/19 5:17 PM EDT", 'DD/MM/YY h:m A', 'America/New_York');
console.log(date.valueOf()); // 1555622220000
console.log(date.format()); // 2019-04-18T17:17:00-04:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
As a side note, remeber that time zone abbreviations are ambiguous, see here for additional info.

can you use "-" instead of "/"with JavaScript Short Date format

On W3Schools, they showed entering a short date format with "/" as follows,
new Date("03/25/2015"). I tried replacing the "/" with "-" as follows,
new Date("03-25-2015") and that worked too. However, in reading through the website, I couldn't find that being mentioned as a valid alternative.
Is it? Even though it worked, is there any reason I should not use it and use the forward slash instead?
If you try using new Date("03-25-2015") in Firefox, you'll get an "invalid date" message. So essentially, using dashes does not work across all browsers. It's better to stick with forward slashes (/).
The same goes with periods between the dates new Date("03.25.2015") is invalid in Firefox but not in Chrome.
According to the ES5 spec, when the Date constructor is passed a string, it will use the same logic as Date.parse:
Let v be ToPrimitive(value).
If Type(v) is String, then
a. Parse v as a date, in exactly the same manner as for the parse method (15.9.4.2); let V be the time value for this date.
Date.parse uses the Date Time String Format first, implementation-specific heuristics second:
The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
The Date Time String Format is YYYY-MM-DDTHH:mm:ss.sssZ. YYYY, YYYY-MM and YYYY-MM-DD are also valid.
As Mottie notes, new Date("03-25-2015") fails in Firefox. However, this is only partly due to the hyphens. If you move the year to the front (new Date("2015-03-25")) the date string will conform to the Date Time String it succeeds.
From MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
One of the ways to create a new Date object is by new Date(dateString);. dateString is described as:
String value representing a date. The string should be in a format recognized by
the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a
version of ISO8601).
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to
browser differences and inconsistencies.
This method of creating a new Date object uses the Date.parse() method to parse the dateString string.
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Date.parse() is defined:
The Date.parse() 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 unrecognised or, in some cases, contains
illegal date values (e.g. 2015-02-31).
ECMAScript 5 ISO-8601 format support
The date time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or
"2011-10-10T14:48:00" (date and time) can be passed and parsed. Where
the string is ISO 8601 date only, the UTC time zone is used to
interpret arguments. If the string is date and time in ISO 8601
format, it will be treated as local.
Therefore, the syntax you used, i.e. new Date("03-25-2015"), is valid syntax, but discouraged due to browser differences and inconsistencies.
When you have questions like this, you should usually go straight to the canonical source to find out. In this case, the canonical source for JavaScript is the EMCAScript specification.
The relevant section is:
http://www.ecma-international.org/ecma-262/6.0/#sec-date.parse
It states:
Date.parse ( string )
[...]
The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
In other words, the only formats guaranteed to be supported across all implementations are listed in Date Time String Format (20.3.1.16). Any formats other than those may or may not work depending on the implementation, and therefore should not be used.
To simplify section 20.3.1.16, the only valid format for dates is YYYY-MM-DD. Not surprisingly, W3Schools used an invalid format in their example.
An alternative source for JavaScript documentation is Mozilla Developer Network (MDN). It is not the canonical source, but is much higher quality than W3Schools and includes direct links to the canonical sources at the bottom of articles.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

How to interpret this date format?

I just found a date format in a javascript document that I have never seen before. It looks like this:
'1978-11-23T00:00:01.000Z'
Can someone explain what that 'T' and 'Z' mean?
Can someone explain what that 'T' and 'Z' mean?
The T is the delimiter between the date and time. The Z is a timezone, specifically timezone "Zulu" (GMT+00:00, e.g., Greenwich mean time). As of the latest specification (ES5), JavaScript has a standard date/time format which is derived from a simplified version of ISO 8601 (although it handles the absence of a timezone differently from the ISO standard). (Prior to ES5, there was no standard string form for dates in JavaScript at all, amazingly.)
How to interpret this date format?
If you're using an engine that implements this part of ES5, you can just pass that string into the Date(value) constructor:
var dt = new Date('1978-11-23T00:00:01.000Z');
If you're using an engine that doesn't yet implement this part of the standard (IE8 or earlier, for instance), you'll have to use a regular expression to break out the individual parts of the string, convert them to numbers, and feed them into the Date(year, month, date, hours, minutes, seconds, ms) constructor, or use an add-on library to parse it for you.

Is it possible to implement a way to "guess" this date format based on the information in the array?

In JavaScript Language ,
I have an array ... maybe it look like this
var all_date = new Array( "11/12/2009", "31/12/2010", "29/12/2011", "17/09/2011" );
Is it possible to implement a way to "guess" this date format based on the information in the array and perhaps suggest to user which date format is most likely? Such as ... DD/MM/YYYY
Well of course, if the data happens to conveniently contain day values greater than 12 and have four-digit years (as the data you've quoted does), you're not guessing, you can be certain you've got the right format.
But if it happens that all of the day values in the data are 12 or lower, it's impossible to be certain whether the data is in U.S. MM/DD/YYYY format or the more common DD/MM/YYYY.
So no, you can't reliably infer the format in the general case. The source of the data should provide the format information (in documentation, etc.), and ideally use a less ambiguous format such as YYYY/MM/DD.
Well, to a certain degree, yes, you can. One obvious method is by using regular expressions. Suppose you have a date, like 2020-10-31, you can test it against a RegExp, extract tokens(year, month and day of month) and once tokens are identified, you can map them to their corresponding format tokens(YYYY, MM and DD).
Now consider the RegExp, /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/; put in simple words, it matches string of the form (4-digit year)-(month, maybe)-(day of month, maybe); parentheses imply capture groups. Capture groups here, will essentially pull out the tokens for you(year, month and day of month parts). Try out the following snippet,
console.log('2020-10-31'.match(/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/));
Once the tokens have been identified, it's easy to construct the format string, YYYY-MM-DD.
Be warned though, if the date is ambiguous, you can't accurately determine token semantics. Consider the date 01/01/2020, it could be any of DD/MM/YYYY or MM/DD/YYYY. Nonetheless, the method works quite well for standard date-time formats(ISO 8601 and RFC 2822).
Detailed references :-
Regular expressions
Here is a snippet from moment.js source code which does what you asked, but only for ISO 8601 compliant dates
Here is a package I wrote, which does the same thing for other formats as well, accounting for the ambiguities.

Categories