Inconsistencies when creating new date objects - javascript

I am creating new date objects in javascript and seeing some inconsistencies depending on whether I use the dateString parameter vs the year/month/day integer parameters.
Here's an example:
var dt1 = new Date(1979,3,5);
var dt2 = new Date('1979-04-05');
jsFiddle with example
dt1 is assigned the value: Thu Apr 05 1979 00:00:00 GMT-0500 (Central Daylight Time)
dt2 is assigned the value: Wed Apr 04 1979 19:00:00 GMT-0500 (Central Daylight Time)
Can someone explain this behavior? The second example (dt2) happens to be the format that Chrome is returning a selected date from input[type=date] elements which is why I'm trying to figure this out.

It looks like the form '1979-04-05' is interpreted as a UTC date (and then that UTC date is converted to local time when displayed). The form new Date(1979,3,5); is interpreted as local time. You can use Date.UTC to force UTC time for the 3-argument form (see docs).
Date parsing (and timezone handling in particular) is generally not uniform across browsers, and it's better not to depend on it - use UTC whenever possible, or use a separate library like Date.js or moment.js.

Related

Javascript Date constructor depending by timezone [duplicate]

This is what I get in chrome console. I pass "2016-09-05"(YYYY-MM-DD) as the date and it shows me Sept 4,2016 as the date.
Another constructor shows the right date
Passing it comma separated needs some tokenizing + parsing + making month zero indexed which I want to avoid
If you omit the time in the new Date(string) constructor, UTC time is assumed. So the displayed value is actually correct. Use new Date('2016-09-05T00:00') to create the date object in local time.
Edit: while some browsers seem to support the yyyy-MM-dd HH:mm format, it's not officially supported, and, as mentioned in the comments, this doesn't work in Safari. I've updated the answer to use a T instead of a space between date and time.
Per the ECMAScript® 2023 Language Specification:
Date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes “date-time” forms that consist of one of the above
date-only forms immediately followed by one of the following time
forms with an optional UTC offset representation appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
You could use the Solution from UTC Date Conversion.
Which basicall does the following:
console.log(new Date("2014-12-23"));
console.log(convertDateToUTC(new Date("2014-12-23")));
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
The output would be like that in the console (for me at least :D)
Tue Dec 23 2014 01:00:00 GMT+0100 (Mitteleuropäische Zeit)
Tue Dec 23 2014 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
use setFullYear the syntax is Date.setFullYear(year,month,day)
mydate = new Date();
mydate.setFullYear(2016, 08, 05);

Changing month digit in Date.UTC() leads to change of timezone

When I run this code, the first date is shown in GMT, and the second in BST. Why is this? The calls to Date.UTC are identical apart from one changed digit, the month digit. That, to me, shouldn't warrant a change in timezone. Please note that I'm in London right now, so somehow the second date seems to be returning local time. Why is the timezone different for the two different dates?
var date1 = new Date(Date.UTC(2005,0,5,4,55,55));
alert(date1); // Wed Jan 05 2005 04:55:55 GMT+0000 (GMT)
var date2 = new Date(Date.UTC(2005,5,5,4,55,55)); // <-- 0 has been replaced by 5
alert(date2); // Sen Jun 05 2005 05:55:55 GMT+0100 (BST)
Using Date.UTC(), only effects setting the date using UTC.
As default Javascript dates display using localtime.
So if you wish to see the dates in UTC format,.
You can't just use the default toString() implementation, as that will use localtime version.
But what you can do is use the UTC variants for display. eg. toUTCString() and also toISOString().
var date2 = new Date(Date.UTC(2005,5,5,4,55,55));
//if you say live in the UK, this date in localtime is
//British Summer Time,..
//eg. Sun Jun 05 2005 05:55:55 GMT+0100 (GMT Summer Time)
//if your running this script from another country
//your likely to see something different.
console.log(date2.toString());
//here we show the date in UTC, it will be same
//whatever country your running this from
//eg. Sun, 05 Jun 2005 04:55:55 GMT
console.log(date2.toUTCString());
//for an easier to parse date,
//eg. 2005-06-05T04:55:55.000Z
console.log(date2.toISOString());

Wrong date with angular material's date picker

I use the datepicker to pick a date and send it to the server.
When I log the JS value I get the correct result:
Tue Mar 22 2016 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
but in the ajax request it is
2016-03-21T23:00:00.000Z
I don't modify the values, just giving the object to angulars http function.
Does Angular need some configuration to handle it?
You can try the following piece of code
dateObj.setMinutes((dateObj.getMinutes() + dateObj.getTimezoneOffset()));
No need of localization, use this code just before doing any service call. It will pass you the exact date what you selected in the datepicker.
It will work in all timezone (+) and (-),
Example: 2016-03-21 00:00:00 GMT+0100, the above said code covert it as 2016-03-21 01:00:00 GMT+0000. While on Service it converts it as 2016-03-21 00:00:00.
I think it will solve your problem.
Those two strings represent the same time. One is in UTC, i.e. GMT +0, which you can see from the Z ending. The other is in a different timezone, specifically GMT +1 hour.
If you had javascript date objects for both strings, and turned them into integers, i.e. seconds passed since Jan 1, 1970, UTC, you'd find them identical. They represent the same instant but in two different geographic locations.
var d1 = new Date('Tue Mar 22 2016 00:00:00 GMT+0100');
var d2 = new Date('2016-03-21T23:00:00.000Z');
Number(d1); // 1458601200000
Number(d2); // 1458601200000
Generally this is a good thing. Dealing in timezones gets very confusing. I find it best for a server to always deal in UTC.
https://github.com/angular/material/pull/9410
Check out the 1.1.1+ version. This will solve your issue.
<md-datepicker ng-model="date" ng-model-options="{ timezone: 'utc' }"></md-datepicker>
If suppose am selecting a date like Tue Aug 06 2019 00:00:00 GMT+0530 (India Standard Time), am getting 2019-08-05T18:30:00.000Z. ( which in my case previous date with respect to the selected date)
I made use of toLocalDateString() to do the job.
// this.date = 2019-08-05T18:30:00.000Z
const converted = new Date(this.date).toLocaleDateString();
console.log(converted); // 8/6/2019 (MM/DD/YYYY) format

Javascript new Date decreases date by a day

I have a scenario where I am using AngularJS to read date. Interestingly it decreases my date value by one.
Why is this happening?
new Date("2016-01-06T00:00:00")
give me result as
Tue Jan 05 2016 16:00:00 GMT-0800 (Pacific Standard Time)
This is because when you use the new Date() in the JavaScript, it converts and prints the date in browsers timezone.
So if you print:
new Date("2016-01-06T00:00:00-0800")
You will get the actual output you want, because of the -0800 difference between your time zone (determined by the browser) and the UTC time.
The UTC time zone is used to interpret arguments in ISO 8601 format that do not contain time zone information (note that ECMAScript 2015 specifies that date time strings without a time zone are to be treated as local, not UTC).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Since your date string appears to lack one, JS assumed it's UTC time. The result you see is the same moment in time, offset to your timezone. All you need to do is provide timezone data to the string you're parsing.
It is because the date is taking your browser's timezone in to account, which in your case is in PST. It does the same to me, in EST:
test = new Date("2016-01-06T00:00:00")
Tue Jan 05 2016 19:00:00 GMT-0500 (EST)
You can still obtain the time in UTC by using any of the .getUTC* functions, like so:
test.getUTCDate();
6

Change timezone of date in Javascript but NOT the date or time

I have a problem here. I need to change the timezone of of a date in Javascript to UTC before passing it to the back end pf my service for validation. I cannot find a solution in any of the questions on this site or on other sites. The problem is that every method I have tried so far is also changing the time and date of my Javascript date object. For example:
var startDate = new Date($("#start-date-picker").val()).toUTCString();
Changes the time which affects the date (the timezone of my laptop is currently set to GMT +2).
While debugging my date object looks like this:
var startDate = new Date(getProperDate($("#start-date-picker").val()));
//startDate = Wed Aug 26 2015 00:00:00 GMT+0200 (Romance Daylight Time) {}
But when changed using the .toUTCString() method the date ends up like this:
startDate2 = "Tue, 25 Aug 2015 22:00:00 GMT"
I cannot find a way to change just the timezone and preserve the current date and time. I cannot use any external libraries either before anyone suggests moment.js or any others. Any help would be much appreciated, thanks!

Categories