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.
Related
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.
I am using moment.js to compare two dates in my javascript code.
The input values are passed from a JSON string.
When I provide date 21/01/2050 00:00 (MM/DD/YYYY HH:mm FORMAT), the resulting date shows as 21/1/1950 00:00.
I tried using the below options:
moment(item["End Date"]).utc().format()
moment(item["Start Date"]).format('MM/DD/YYYY HH:mm')
moment(new Date(item["Start Date"])).format('MM/DD/YYYY HH:mm')
But these are still giving me year as 1950 instead of 2050.
Is there a way to format this one correctly?
Since your input is not in ISO 8601 or RFC 2822 format recognized by 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 have to use moment(String, String), passing 'DD/MM/YYYY HH:mm' as second argument.
Here a live sample:
var input = "21/01/2050 00:00";
console.log( moment(input, 'DD/MM/YYYY HH:mm').format('MM/DD/YYYY HH:mm') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
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
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.
Why Date.parse("2011-11-15") considers current time zone in Web browser, and Date.parse("2011/11/15") does not? Why the results are different?
The first form is being considered as an ISO date in UTC, according to section 15.9.1.15 of ECMA-262. The second form is being considered in an implementation-specific way, as per section 15.9.4.2:
The parse function applies the ToString operator to its argument and interprets the resulting String as a date
and time; it returns a Number, the UTC time value corresponding to the date and time. 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
So I suspect "2011/11/15" is being converted to the local midnight of November 15th, whereas "2011-11-15" is being converted to UTC midnight of November 15th.
from date.parse documentation
the date/time string may be in ISO 8601 format. Starting with
JavaScript 1.8.5 / Firefox 4, a subset of ISO 8601 is supported. For
example, "2011-10-10" (just date) or "2011-10-10T14:48:00 (date and
time) can be passed and parsed. Timezones in ISO dates are not yet
supported, so e.g. "2011-10-10T14:48:00+0200" (with timezone) does not
give the intended result yet.