JavaScript Date constructor and UTC - javascript

If I use new Date('2015-01-01'), will that give me a point in time equivalent to 2015-01-01T00:00:00Z?

From documentation:
constructors: ... dateString 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).
From documentation on Date.parse():
If a time zone is not specified and the string is in an ISO format
recognized by ES5, UTC is assumed
However, depending on this behaviour could be risky, as, from the same document:
note that ECMAScript ed 6 draft specifies that date time strings without a time zone are to be treated as local, not UTC

Related

Difference in new Date() output in Javascript

I tried with two methods to generate Date first by passing whole date string and second with year, month, day combination. But I am getting different outputs while the same date is being provided. The Day is not right. It should be 30 June in the first too.
const oldDate = new Date('2020-06-30');
const newDate = new Date('2020', '05', '30');
console.log(oldDate.toString(), newDate.toString());
When you instantiate a Date by passing a string, it's supposed to be a full ISO 8601 string which specifies the time zone. As you dont specify it, it takes GMT+0, and you seem to be located at GMT-7. You should write this instead:
console.log(new Date('2020-06-30T00:00:00-07:00').toString());
The Date constructor that accepts multiple arguments expects them to be numbers, and accepts the month number as a 0-based value (0 = January). The values are expected to be in local time.
The Date constructor accepting a single string argument parses the string according to the specified rules (which apply to your example) and, possibly, unspecified fallback rules the JavaScript engine implementer chose to add (in your case, though, the fallback isn't necessary). When there's no timezone indicator on the string, Date-only forms such as yours are parsed in UTC (date/time forms are parsed in local time).
(The Date constructor accepting a single number expects that number to be milliseconds-since-The-Epoch [Jan 1st, 1970 at midnight, UTC].)
Below format is considered as GMT time and it tries to convert to your local timezone. That's why you notice 7 hours subtracted.
new Date('2020-06-30')
whereas,
Below format is considered as local timezone and no further conversion happen.
new Date('2020', '05', '30');
According to MDN docs:
dateString
A string value representing a date, specified in a format recognized by the Date.parse() method. (These formats are IETF-compliant RFC 2822 timestamps, and also strings in a version of ISO8601.)
Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.
Support for RFC 2822 format strings is by convention only.
Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Therefore, when you create date via new Date("2020-06-30") it creates date object in 0 timezone and adjusts time to show it equal to your time zone.

What format of date/time object does moment js accept?

moment("2019-08-22T09:00:00") successfully creates a Moment object, but if I try to do moment("9:00") it doesn't. If I've provided only the hour like that, I have to do moment("9:00", "h:mm").
My Question Is:
What format(s) of date/time string do I have to pass to moment() in order to not have to specify the format, as I did with moment("9:00", "h:mm")?
From documentation:
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.
You can see on the moment's document, there are three categories of tokens can be used in the format:
Week year, week, and weekday tokens
Locale aware formats
Hour, minute, second, millisecond, and offset tokens
You need to pass a second argument to moment() using a .format() method
Try this:
moment("2019-08-22T09:00:00").format('MM/DD/YYYY');

Initialize JS date object from HTML date picker: incorrect date returned

How do you correctly intitialize a timezone-independent date (or I guess a date that is fixed to a single timezone across the html side and the JS side) from a html datepicker?
I have the following simple code, which is producing incorrect dates:
function printDate(){
let d = new Date(document.getElementById("date").value)
alert(d)
}
document.getElementById("printDate").addEventListener("click", e => printDate())
<html>
<body>
Print Date: <br><input type="date" id="date"> <button id="printDate">Add</button>
</body>
</html>
But at least on my computer, currently sitting in U.S. mountain time, it produces incorrect dates. I give it today's date (March 9, 2019), and it alerts yesterday's date in the following format: Fri Mar 08 2019 17:00:00 GMT-0700 (MST). How do I make it not do that?
I really just want it to assume that all input and all output are in GMT.
In a <input type="date" /> element, the selected date is displayed in the locale format, but the value property is always returned in yyyy-mm-dd format, as described in the MDN docs.
In other words, when you choose March 9, 2019, you may see 03/09/2019 from the US or 09/03/2019 in other parts of the world, but value is 2019-03-09 regardless of any time zone or localization settings. This is a good thing, as it allows you to work with the selected date in a standard ISO 8601 format, without trying to apply a time.
However, when you parse a date string in that format with the Date object's constructor (or with Date.parse), you run up against a known issue: The date is not treated as local time, but as UTC. This is the opposite of ISO 8601.
This is described in the MDN docs:
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
It's also in the ECMAScript specification (emphasis mine):
... When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
There was a debate about this in 2015, but ultimately it was decided that maintaining compatibility with existing behaviors was more important than being ISO 8601 compliant.
Going back to your question, the best thing to do would be to not parse it into a Date object if you don't need one. In other words:
function printDate(){
const d = document.getElementById("date").value;
alert(d);
}
If you really need a Date object, then the easiest option is to parse the value yourself:
function printDate(){
const parts = document.getElementById("date").value.split('-');
const d = new Date(+parts[0], parts[1]-1, +parts[2], 12);
alert(d);
}
Note the ,12 at the end sets the time to noon instead of midnight. This is optional, but it avoids situations of getting the wrong day when midnight doesn't exist in the local time zone where DST transitions at midnight (Brazil, Cuba, etc.).
Then there's your last comment:
I really just want it to assume that all input and all output are in GMT.
That's a bit different than what you showed. If really that's what you want, then you can construct the Date object as you previously did, and use .toISOString(), .toGMTString(), or .toLocaleString(undefined, {timeZone: 'UTC'})
function printDate(){
const d = new Date(document.getElementById("date").value); // will treat input as UTC
// will output as UTC in ISO 8601 format
alert(d.toISOString());
// will output as UTC in an implementation dependent format
alert(d.toGMTString());
// will output as UTC in a locale specific format
alert(d.toLocaleString(undefined, {timeZone: 'UTC'}));
}

How fix Invalid date in JS?

Need format my date
When I try do following:
var d = new Date('15.01.2019');
console.log(d);
I get 'Invalid Date' message
If there is other date, for example '01.15.2019' all is correct
How can I solve this problem?
The constructor new Date(dateString) uses the Date.parse() method for parsing the date string. According to documentation of this method, you should use an ISO 8601 compliant date, or a simplification of ISO 8601, which in your case would be YEAR-MONTH-DAY, for example, 2015-01-15.
Other formats may work but are not reliable, as per the documentation:
"Other formats are accepted, but results are implementation-dependent."
It means that using date strings that are not ISO 8601 compliant or simplifications may result in different behaviour across different JavaScript engines and web browsers. It may also vary with the user set's locale.
Use an ISO 8601 simplified string and you will be fine.

Javascript getFullYear() returns the wrong year [duplicate]

This question already has answers here:
JavaScript's getDate returns wrong date
(12 answers)
Closed 6 years ago.
This is so basic, but it makes no sense to me:
new Date("2010-01-01").getFullYear();
result: 2009
wth? My goal is to reformat the date as mm/dd/yyyy given the format yyyy-mm-dd..
Adding on:
new Date("2010-01-01").getMonth();
result: 11
new Date("2010-01-01").getDate();
result: 31
The date string you're passing into new Date() has no timezone in it. It's being interpreted as UTC. The critical thing to understand here is that a Date is stored as a Unix timestamp (seconds since 1970-01-01 00:00, making 'Date' a misleading name) so if you don't specify the time within the date, it's going to apply a default.
Date.prototype.getFullYear() retrieves the full year for that timestamp in your LOCAL time. (See the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear)
You're somewhere west of UTC, and 2010-01-01 UTC is 2009-12-31 in your local time.
And for your final mystery....getMonth() is 0-based, not 1-based, so '11' is December.
Don't use the Date constructor to parse strings, it's largely implementation dependent and inconsistent.
An ISO 8601 date and time without a timezone like "2016-02-29T12:00:00" should be treated as local (i.e. use the host system timezone offset to create a Date), but a date–only string is treated like "2016-02-29" as UTC. The first behaviour is consistent with ISO 8601, but the second isn't.
Some versions of browsers will treat date–only strings as UTC, and some as invalid dates, so always parse strings manually (a two line function or library can help). That way you know how it will be parsed in all hosts.
Provide Time with date in the new Date() as parameter . Then u will get exact Result.

Categories

Resources