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.
Related
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.
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
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
2014-07-29T16:55:46.657Z
I believe it to be:
YEAR-MONTH-DAYTHOURS:MINUTES:SECONDS.MILLISECONDSZ
What is the purpose and full name of T and Z?
Do they just serve as escape characters?
T separates date and time; Z specifies a UTC timezone. (In place of it, -08:00 can appear, for example.)
JSON has no notion of dates, and so if you do JSON.stringify(new Date()), you're in effect doing JSON.stringify(new Date().toJSON()) (link to spec), which gives the date using JavaScript's date/time format. You can get all the gory details about that format in §15.9.1.15 of the spec.
JavaScript's pseudo-ISO-8601 date/time format uses T as the separator between dates and times, and Z as the indicator of UTC (sometimes called GMT). In JavaScript, without the Z, that would still be in UTC (whereas in ISO-8601, it would be "local time"). Instead of the Z, you can specify a timezone offset.
(new Date('2012-12-01')).getMonth() is 10 instead of 11 (getMonth is 0-indexed). I've tested on Firefox, Chrome, and Node.js. Why does this happen?
You are experiencing a timezone issue. Your JS engine interprets the string as UTC, since it was no further specified. From the specification of Date.parse (which is used by new Date):
The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. 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.
In your timezone, the datetime is Nov 30 2012 19:00:00 GMT-0500 - in November. Use .getUTCMonth() and you would get December. However, never trust Date.parse, every browser does it differently. So if you are not in a restricted environments like Node.js, you always should parse your string (e.g. with regex) and feed it to new Date(Date.UTC(year, month, date, …)).
For Firefox's case, at least, RFC2822 states that date specifications must be separated by Folding White Space. Try (new Date('2012 12 01')).getMonth(); Usage of - as a separator does not appear to be defined.
The error is arising from prefixing the day 01 with 0. Not sure WHY this is, but if you remove the zero before the 1, it gives you the right month (11).
Also, it starts giving the wrong month at October if that means anything.
Short term fix, use 1 instead of 01.