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

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

Related

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.

Convert java date into angular date

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

valid date is coming as output from invalida date Javascript [duplicate]

This question already has answers here:
JavaScript Detecting Valid Dates
(5 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 6 years ago.
I am unable to understand why javascript is giving valid date equals to 1 dec date when giving invalid date? Is this behaviour incorporated in language for specific reason? because it must be invalid date for my use case
new Date("11/31/2017")
First of all, the Date constructor is not designed to validate input, or even to be picky. On the contrary, it's explicitly designed to create an instance at any cost, with creative rules like this:
Where Date is called as a constructor with more than one argument, if
values are greater than their logical range (e.g. 13 is provided as
the month value or 70 for the minute value), the adjacent value will
be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new
Date(2014, 1, 1)
So if you really need to validate dates you need to look somewhere else.
As about 11/31/2017, the constructor expects this:
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).
... which looks good. But this follows (emphasis mine):
parsing of date strings with the Date constructor (and Date.parse,
they are equivalent) is strongly discouraged due to browser
differences and inconsistencies.
And if we dig into Date.parse() docs we finally read this:
The ECMAScript specification states: If the String does not conform to
the standard format the function may fall back to any
implementation–specific heuristics or implementation–specific parsing
algorithm. Unrecognizable strings or dates containing illegal element
values in ISO formatted strings shall cause Date.parse() to return
NaN.
However, invalid values in date strings not recognized as ISO format
as defined by ECMA-262 may or may not result in NaN, depending on the
browser and values provided, e.g.:
// Non-ISO string with invalid date values
new Date('23/25/2014');
will be treated as a local date of 25 November, 2015 in Firefox 30 and
an invalid date in Safari 7
This fallback case is the one your date fell into.

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.

Different Date.parse results for 2011-11-15 and 2011/11/15

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.

Categories