Javascript getFullYear() Date method weird behavior - javascript

Can anyone explain why getFullYear does not return 2014?
console.log(new Date('2014-01-01').getFullYear()) //2013
console.log(new Date('2014-01-01').getUTCFullYear()) //2014

From MDN:
The dateString of "March 7, 2014" returns a different date than "2014-03-07" unless the local time-zone is UTC. When converting a dateString of "March 7, 2014" the local time-zone is assumed. When converting a dateString of "2014-03-07" the UTC time-zone is assumed. This results in two different Date values depending on the format of the string that is being converted.
So when you ask it to parse "2014-01-01", you're getting the time in UTC.
Then you call .getFullYear() on your object, which uses local time. If you live in the Eastern US like I do, then it basically subtracts 4 hours from the internal time and returns the year.
So here's what happens:
"2014-01-01" is converted to "1388534400000"
.getFullYear() is called and "1388534400000" is converted to local time
Local time is something like "1388534160000"
New years hasn't yet occurred at "1388534160000", so it's still 2013
All of this implies that if we do something like
console.log(new Date('January 1, 2014').getUTCFullYear()); // 2014
console.log(new Date('January 1, 2014').getFullYear()); // 2014
We'll get the same year, because we told the browser to use our timezone right on New Year's, but they're not equivalent:
console.log(new Date('January 1, 2014').getUTCHours()); // 5
console.log(new Date('January 1, 2014').getHours()); // 0

According to this:
"The difference is when you specify a string in the format YYYY-MM-DD, you get a date that is 12am in the GMT timezone and when you specify a date in the format DD-MM-YYYY, you get a date that is 12am in your current timezone."
So basically since you are specifying News Years Day 2014 when it gets converted from GMT to your local time it believes it is 12-31-13 not 01-01-14.

Related

Moment.js - UTC date to millis since unix epoch

I am trying to get an UTC Date using the moment.js library (just to send it to my server), as follows:
const eighteenYearsAgoUTC = moment().utc().subtract(18, "years").toDate();
const eighteenYearsAgoUTCSinceUnixEpoch = eighteenYearsAgoUTC.valueOf()
console.log(eighteenYearsAgoUTCSinceUnixEpoch);
The millis since unix epoch are: 1051875596343
But... if I do the same without utc, I get the same result
const eighteenYearsAgoUTC = moment().subtract(18, "years").toDate();
const eighteenYearsAgoUTCSinceUnixEpoch = eighteenYearsAgoUTC.valueOf()
console.log(eighteenYearsAgoUTCSinceUnixEpoch);
1051875596343
Why am I getting the same milliseconds since Unix Epoch for an UTC date and a local Date?
My local date is: Fri May 02 2003 13:37:00 GMT+0200 (Central Europe)
The utc method just changes how moment parses and formats dates. The underlying information is still the same.
Milliseconds-since-The-Epoch values are always UTC. Both of your code snippets do the same thing:
Get "now"
Subtract 18 years
Get the result as the milliseconds-since-The-Epoch value
You'd notice a difference if you were formatting a date or parsing one, but you aren't doing either of those things.

getFullYear on ISO date

I need to getFullYear on a JavaScript Date, however newing up a Date() creates it at UTC, and in the cases of January 1, it becomes LAST YEAR. (at my timezone, EST)
so:
startDateYear = new Date('2019-01-01').getFullYear()
returns 2018
I know .getISODate() does get the true date in my timezone, but I need to come up with a way to chain .getISODate() with .getFullYear() to get the true year.

Why .toISOString() gives different time?

Why this sample give me 22 number instead client 23 number:
console.log(new Date().toISOString());
Output is: 2019-01-22T22:58:46.606Z
Client side time:
The toISOString() method always outputs the time in UTC. From the docs:
The timezone is always zero UTC offset, as denoted by the suffix "Z".
In this case, the date is still the 22nd in UTC but, in your timezone, it's already the 23rd.
The Date object you have here is still in your local timezone, though. It just happens that the toISOString() method always outputs a UTC representation. If you do the following, you should see the date you're expecting:
console.log(new Date().toLocaleString()) // "1/22/2019, 3:14:18 PM" for me (US Pacific Time)
toISOString() returns a date/time in ISO format with timezone as UTC +0.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Just to add on to what's already been offered. You still need to be careful about using the Date() method. It can generate different dates depending on what you give it.
//This outputs midnight (12:00AM) on January 22nd in the UTC timezone
new Date('2019-01-22').toISOString() // output: "2019-01-22T00:00:00.000Z"
//This outputs 5:00AM on January 22nd in the UTC timezone because my PC is in the
//Eastern Standard timezone and I used a different format for my date string.
new Date('01/22/2019').toISOString() // output: "2019-01-22T05:00:00.000Z"

Issue about the return value of getTime()

I have created a date variable pointing to 9th of July 2014
var date = new Date(2014, 6, 9);
When I try to obtain the time from this date, I expect that the time variable
var time = date.getTime();
would give me the value milliseconds value of July 9th 2014 at 00:00:00.
Instead it gives me
1404860400000
which is the milliseconds value of 8th July 2014 at 23:00:00.
Can someone explain me why this?
Your code here:
var date = new Date(2014, 6, 9);
creates a Date instance initialized to your local time of midnight on July 9th, 2014. Timestamp numbers (both JavaScript's milliseconds-since-the-Epoch and Unix's seconds-since-the-epoch) are unaffected by timezones, the value is since midnight Jan 1 1970 UTC.
If you were to construct this date:
var newDate = new Date(1404860400000);
...you'd have a date that was exactly equivalent to your first one. If you asked it for the local version of the moment it represented, it would say midnight on July 9th, 2014.
In both date and newDate above, if you ask it the UTC version of the date, you'll see it's offset from midnight (the direction depends on where you are, west or east of Greenwich, England). At the moment I'm writing this, almost no one is on GMT, not even those of us in the UK who normally are, because of Summer time. But for most people who are never in GMT, the value will always be offset.
If you want a Date instance giving you midnight on July 9th, 2014 UTC (e.g., not local time), use new Date(Date.UTC(2014, 6, 9)). Date.UTC gives you the time value for the given date in UTC, and then if you feed that time value into new Date, you get a Date for it.
January 1, 1970 :
getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. Returns: the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.
Google.
The Mozilla docs usually cover documentation issues like this quite well.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Trouble converting time to UTC for highstocks

I'm having the hardest time trying to convert this date from an API to UTC milliseconds. As of right now I'm displaying the dates but it's showing 7 hours ahead and going on to the next day which I don't even have data for. Here is the example format:
8/31/2012 9:00:00 AM
I currently have this code
var formattedDate = new Date(data[i].Time);
formattedDate = formattedDate.getTime();
which seems like it's returning the correct value type but the date is wrong. I've also tried
getUTCMilliseconds() and returns 0.
EDIT: jsfiddle example : http://jsfiddle.net/b2NK6/
So you want the raw timestamp in UTC time, instead of local time?
Compare:
(new Date(Date.UTC(2012, 7, 31, 9, 0, 0, 0))).getTime(); /* month 7 is August */
with
(new Date(Date.parse("8/31/2012 9:00:00 AM"))).getTime();
When you parse the string (the second example) it applies your local timezone information when it creates the date object. If you are in timezone -0700, then the date that is created will actually correspond to 4:00pm UTC.
But if you create the date object by explicitly saying that you are specifying the UTC value, it will give you 9:00am UTC, which corresponds to 2:00am in timezone -0700.
Edited to give clearer and more correct code example.
var dateString = "8/31/2012 9:00:00 AM"; // assuming this is expressed in local time
var millisecondsSinceTheEpoch = (new Date(dateString)).valueOf(); // 1346418000000
var isoString = (new Date(millisecondsSinceTheEpoch)).toISOString(); // 2012-08-31T13:00:00.000Z
// Note: example return values from a computer on U.S. Eastern Daylight Time (-4:00).
From W3Schools:
The valueOf() method returns the primitive value of a Date object.
Note: The primitive value is returned as the number of millisecond[s] since midnight January 1, 1970 UTC.
Also see W3Schools for a comprehensive overview of the Date object.
HighStocks expects to get its dates aligned to UTC-midnight date boundary.
Assuming your chart only deals with dates (without the time component) here is a trick you can use:
Do originalDate.getTime() to get the number of milliseconds since midnight UTC 1/1/1970 , e.g. 1362286800000.
Divide the number of milliseconds by (1000*60*60*24) to get the number of days since midnight UTC 1/1/1970 e.g. 15767.208333333334.
Do Math.round() to round the number to the nearest UTC midnight, e.g. 15767.
Multiply the number by (1000*60*60*24) to get it back into the milliseconds scale e.g. 1362268800000.
Here is the final formula:
var utcMidnight=new Date(Math.round(anyZoneMidnight.getTime()/86400000)*86400000)

Categories