Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTC Times in JavaScript

Tags:

javascript

I am trying to get the current UTC date to store in my database. My local time is 9:11 p.m. This equates to 1:11 a.m. UTC. When I look in my database, I notice that 1:11 p.m. is getting written to. I'm confused. In order to get the UTC time in JavaScript, I'm using the following code:

var currentDate = new Date();
var utcDate = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds());
var result = new Date(utcDate);

What am I doing wrong?

like image 227
JavaScript Developer Avatar asked May 21 '12 01:05

JavaScript Developer


1 Answers

A lttle searching turned out you can do this:

var now = new Date(),
    utcDate = new Date(
        now.getUTCFullYear(),
        now.getUTCMonth(),
        now.getUTCDate(),
        now.getUTCHours(),
        now.getUTCMinutes(), 
        now.getUTCSeconds()
    );

Even shorter:

var utcDate = new Date(new Date().toUTCString().substr(0, 25));

How do you convert a JavaScript date to UTC?

It is a commonly used way, instead of creating a ISO8601 string, to get date and time of UTC out. Because if you use a string, then you'll not be able to use every single native methods of Date(), and some people might use regex for that, which is slower than native ways.

But if you are storing it in some kind of database like localstorage, a ISO8601 string is recommended because it can also save timezone offsets, but in your case every date is turned into UTC, so timezone really does not matter.

like image 147
Derek 朕會功夫 Avatar answered Oct 25 '22 01:10

Derek 朕會功夫