Convert date to string in JavaScript - 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.

Related

What is the time format used in Date constructor in nodejs?

I am running Nodejs in Lambda in Sydney region. I have below code:
> d=new Date('2020-12-14T13:20:44.733Z')
2020-12-14T13:20:44.733Z
> d.getDate()
15
It creates a Date instance with a date string 2020-12-14T13:20:44.733Z. But the date is translated to 15th of December not 14th. Does this mean the string 2020-12-14T13:20:44.733Z representing UTC time?
The process that is carried out is described in the specification here:
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 calendar date extended format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
Z is the UTC offset representation specified as "Z" (for UTC with no offset) or an offset of either "+" or "-" followed by a time expression HH:mm (indicating local time ahead of or behind UTC, respectively)
So the trailing Z means the time passed into the Date constructor is in UTC, but getDate will give you the local representation of whatever time is in the Date object.

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.

Moment.js converting the date incorrectly in case of future dates

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>

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

Parse date string with different date format

I would like to know how to parse date strings that could have different date format.
For now I do the following to parse my date strings:
var parseDate = d3.time.format("%Y-%m-%d %H:%M").parse;
How to specify multiple date format to my parseDate function?
new Date('YOUR DATE STRING')
Also checkout moment.js,
You can use moment('YOUR DATE STRING')
moment will try to interpret the String according to standard formats, if not it will fall back to Javascript's native Date() constructor.
This should work for standard ISO format or a variety of commonly seen date formats. Obviously it is not magic and will not understand all possible permutations of YYYY MM and DD

Categories