toLocaleDateString() is subtracting a day - javascript

I'm pulling dates from a SQL database which treats them as dates that start at midnight. When I go to use toLocaleDateString() on them, it formats them properly, however not before losing a day.
Before formatting: 2011-09-01T00:00:00
After formatting: 8/31/2011
Code:
plan.dateReceived = new Date(plan.dateReceived).toLocaleDateString()+','+plan.dateReceived;
Why does it do this, and what inline fix can I make to have it behave properly?
I also found another post that had a similar problem, but I'm not 100% convinced that it's a timezone issue.

If you run the code in pieces, you'll notice that new Date('2011-09-01T00:00:00') produces output like Wed Aug 31 2011 20:00:00 GMT-0400 (EDT) (my computer is in EDT right now).
This is because (doc):
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time
zone, but given an ISO format such as "2014-03-07" it will assume a
time zone of UTC. Therefore Date objects produced using those strings
will represent different moments in time unless the system is set with
a local time zone of UTC. This means that two date strings that appear
equivalent may result in two different values depending on the format
of the string that is being converted (this behavior is changed in
ECMAScript ed 6 so that both will be treated as local).
Converting that to the locale date string will convert it to a string appropriate for the browser's locale. Documentation indicates that "the default is the runtime's default time zone".
If you want to ensure the string is in UTC time, use
new Date('2011-09-01T00:00:00').toLocaleDateString('en-US', {timeZone: 'UTC'})

We experienced this problem on Google Chrome v87.0.4280 IOS, but not on a computer with the same browser.
The problem was that the timezone string did not contain a Z at the end.
"Z" is kind of a unique case for DateTimes. The literal "Z" is
actually part of the ISO 8601 datetime standard for UTC times. When
"Z" (Zulu) is tacked on the end of a time, it indicates that that time
is UTC, so really the literal Z is part of the time.
Appending Z to the datetime fixed the problem.
new Date('2011-09-01T00:00:00Z').toLocaleDateString('en-US', {timeZone: 'UTC'})

Related

When formatting date object - does it matter that the T and the 000Z will be removed when storing to db?

Sorry if its a very basic question but I dont understand the following:
When I format the Date object (no matter what library I used), I get a string.
from this: 2022-11-28T16:55:44.000Z (new Date object)
I get this: 2022-11-28 16:55:44 (or other formats obviously depending how I format it)
Even if I turn it back into an object it, the T and 000Z will never be there anymore. Do I just ignore that (seems like it as any library or date methods are ignoring the T and the string ending when formatting) or do I add it 'back' Isnt it a problem if dates stored in my db are different (for later queries etc.)?
The Z indicates UTC (Coordinated Universal Time, also known as Greenwich Meridian Time), dropping that changes the meaning - unless your browser or server lives in the Greenwich time zone and it is winter (no daylight saving time).
You can convert back and forth between a Date object and a UTC string as follows (my browser lives in the Central European time zone):
> utc = '2022-11-28T16:55:44.000Z'
'2022-11-28T16:55:44.000Z'
> d = new Date(utc)
Mon Nov 28 2022 17:55:44 GMT+0100 (Central European Standard Time)
> d.toISOString()
'2022-11-28T16:55:44.000Z'
Alternatively, you can convert back and forth between a Date object and a formatted string in your browser's or server's time zone (the last line shows that my browser's format differs from yours):
> formatted = '2022-11-28 17:55:44'
'2022-11-28 17:55:44'
> d = new Date(formatted)
Mon Nov 28 2022 17:55:44 GMT+0100 (Central European Standard Time)
> d.toLocaleString()
'11/28/2022, 5:55:44 PM'
But you should not store the Date objects in this format in a database, unless you can guarantee that they are always read and written in the same time zone. For example, if you format a Date object with your browser (in CET) and store it, then someone else who reads it and converts it back to a Date object with their browser in the New Zealand time zone will see a wrong value. Also, dates like 9/11/2022 are ambiguous if the formatting rules are not clear (September 11th or November 9th?).
That's why I would prefer UTC strings when storing Date objects and use formatted strings only for outputting them to the user and for parsing user input.
I see it even stronger: You should never store dates as strings, it's a design flaw. Store always proper Date objects. Here on SO you can find hundreds of questions, where people have problems, because they stored date values as (localized) strings. It is not limited to MongoDB, it applies to any database.
Date objects in MongoDB are UTC times - always and only! Usually the client application is responsible to display the date/time in local time zone and local format.
What do you mean by "turn it back", i.e. how do you do it?
You should not rely on new Date(<string>) without time zone. Some browsers/environments may apply UTC time, others may use current local time zone, see Differences in assumed time zone
Have a look at 3rd party date libraries, e.g. moment.js, Luxon, or Day.js. Usually they provide better control how to parse strings and time zones.

javascript date not returning correctly [duplicate]

I'm pulling dates from a SQL database which treats them as dates that start at midnight. When I go to use toLocaleDateString() on them, it formats them properly, however not before losing a day.
Before formatting: 2011-09-01T00:00:00
After formatting: 8/31/2011
Code:
plan.dateReceived = new Date(plan.dateReceived).toLocaleDateString()+','+plan.dateReceived;
Why does it do this, and what inline fix can I make to have it behave properly?
I also found another post that had a similar problem, but I'm not 100% convinced that it's a timezone issue.
If you run the code in pieces, you'll notice that new Date('2011-09-01T00:00:00') produces output like Wed Aug 31 2011 20:00:00 GMT-0400 (EDT) (my computer is in EDT right now).
This is because (doc):
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time
zone, but given an ISO format such as "2014-03-07" it will assume a
time zone of UTC. Therefore Date objects produced using those strings
will represent different moments in time unless the system is set with
a local time zone of UTC. This means that two date strings that appear
equivalent may result in two different values depending on the format
of the string that is being converted (this behavior is changed in
ECMAScript ed 6 so that both will be treated as local).
Converting that to the locale date string will convert it to a string appropriate for the browser's locale. Documentation indicates that "the default is the runtime's default time zone".
If you want to ensure the string is in UTC time, use
new Date('2011-09-01T00:00:00').toLocaleDateString('en-US', {timeZone: 'UTC'})
We experienced this problem on Google Chrome v87.0.4280 IOS, but not on a computer with the same browser.
The problem was that the timezone string did not contain a Z at the end.
"Z" is kind of a unique case for DateTimes. The literal "Z" is
actually part of the ISO 8601 datetime standard for UTC times. When
"Z" (Zulu) is tacked on the end of a time, it indicates that that time
is UTC, so really the literal Z is part of the time.
Appending Z to the datetime fixed the problem.
new Date('2011-09-01T00:00:00Z').toLocaleDateString('en-US', {timeZone: 'UTC'})

How to convert date time saved in New York timezone to local time zone in javascript?

I am getting date time stored as string in New York timezone (GMT -4) format from third-party website. I want to convert it to local time zone using javascript. Date time is saved in following format
"2019-04-15 19:09:16"
I know i can achieve this through MomentJS but I want to know if there is any simple solution beside loading all library to convert date time to local timezone.
On Chrome expected output could be achieved by appending GMT-4 at the end of date and
new Date("2019-04-15 19:09:16 GMT-4")
But this solution doesn't work on Firefox because of invalid format.
If you actually know that the offset is UTC-4, then you simply need to reformat your string to be compliant with the ECMAScript Date Time String Format, which is a simplification of the ISO 8601 Extended Format.
new Date("2019-04-15T19:09:16-04:00")
However, note that New York is on US Eastern Time, which is actually in daylight saving time for the date and time you provided. In other words, it isn't UTC-4 (EST), but rather UTC-5 (EDT). So for that example, it should be:
new Date("2019-04-15T19:09:16-05:00")
But what if you don't know which offset it is for a given time zone on a particular date and time? After all, time zones, daylight saving time transitions, and associated offset are different all over the world, and have changed throughout history. So one cannot just assume a time zone has a single number that is its offset. (Read more under "Time Zone != Offset" in the timezone tag wiki.)
Presently, JavaScript cannot help you with that on its own. Instead, you'll need to use a library, such as the ones referenced here.
For example, using Luxon, you can do the following:
luxon.DateTime.fromISO("2019-04-15T19:09:16", { zone: "America/New_York" }).toJSDate()
In the future, we hope to solve this in the JavaScript language via Temporal objects - which are still in the ECMAScript proposal stage.

Safari and Chrome showing different results of new Date() [duplicate]

I want to convert date string to Date by javascript, use this code:
var date = new Date('2013-02-27T17:00:00');
alert(date);
'2013-02-27T17:00:00' is UTC time in JSON object from server.
But the result of above code is different between Firefox and Chrome:
Firefox returns:
Wed Feb 27 2013 17:00:00 GMT+0700 (SE Asia Standard Time)
Chrome returns:
Thu Feb 28 2013 00:00:00 GMT+0700 (SE Asia Standard Time)
It's different 1 day, the correct result I would expect is the result from Chrome.
Demo code: http://jsfiddle.net/xHtqa/2/
How can I fix this problem to get the same result from both?
The correct format for UTC would be 2013-02-27T17:00:00Z (Z is for Zulu Time). Append Z if not present to get correct UTC datetime string.
Yeah, unfortunately the date-parsing algorithms are implementation-dependent. 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.
To make the Date constructor not (maybe) use the local timezone, use a datetime string with timezone information, e.g. "2013-02-27T17:00:00Z". However, it is hard to find a format that is reliable parsed by every browser - the ISO format is not recognised by IE<8 (see JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse). Better, use a unix timestamp, i.e. milliseconds since unix epoch, or use a regular expression to break the string down in its parts and then feed those into Date.UTC.
I found one thing here. It seems the native Firefox Inspector Console might have a bug:
If I run "new Date()" in the native Inspector, it shows a date with wrong timezone, GMT locale, but running the same command in the Firebug Extension Console, the date shown uses my correct timezone (GMT-3:00).
Noticed that FireFox wasn't returning the same result as Chrome. Looks like the format you use in kendo.toString for date makes a difference.
The last console result is what I needed:
Try using moment.js. It goes very well and in similar fashion with all the browsers. comes with many formatting options. use moment('date').format("") instead of New Date('date')

ExtJS dates and timezones

I have a problem with the Ext Date class seemingly returning the wrong timezone for a parsed date. Using the code below I create a date object for the 24th May, 1966 15:46 BST:
date = "1966-05-24T15:46:01+0100";
var pDate = Date.parseDate(date, "Y-m-d\\TH:i:sO", false);
I then call this:
console.log(pDate.getGMTOffset());
I am expecting to get the offset associated with the orignal date back (which is GMT + 1), but instead I get the local timezone of the browser instead. If the browser is set to a timezone far enough ahead GMT, the day portion of the date will also be rolled over (so the date will now appear as 25th May, 1966).
Does anyone know how to get around this and get Ext to recognise the correct timezone of the parsed date rather than the local browser timezone?
If this is not possible, can Ext be forced to use GMT rather than trying to interpret timezones?
I checked the parseDate() implementation in ExtJS source code and the documentation of Date in core JavaScript, the Date() constructor used by ExtJS does not support time zone information. JavaScript Date objects represent a UTC value, without the time zone. During parsing in ExtJS source code, the time zone is lost while the corresponding offset in minutes/seconds is added to the Date.
I then checked the source code of getGMTOffset() defined by ExtJS: it builds a time-zone string using the getTimezoneOffset() function defined in JavaScript.
Quoting the documentation of getTimezoneOffset():
The time-zone offset is the difference
between local time and Greenwich Mean
Time (GMT). Daylight savings time
prevents this value from being a
constant.
The time-zone is not a variable stored in the Date, it is a value that varies according to the period of the year that the Date falls in.
On my computer, with a French locale,
new Date(2010,1,20).getTimezoneOffset()
// -60
new Date(2010,9,20).getTimezoneOffset()
// -120
Edit: this behavior is not specific to Date parsing in ExtJS, the following note in the documentation of Date.parse() on Mozilla Doc Center is relevant here as well:
Note that while time zone specifiers
are used during date string parsing to
properly interpret the argument, they
do not affect the value returned,
which is always the number of
milliseconds between January 1, 1970
00:00:00 UTC and the point in time
represented by the argument.
I'm a little late but in latest ExtJS, you can pass an optional boolean to prevent the "rollover" in JS
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Date-method-parse
My two cents, because I can't really set all my time to 12:00 like Tim did. I posted on the sencha forum

Categories

Resources