Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: wrong UTC time

Tags:

javascript

utc

I have a unix timestamp. I want to render it as UTC time

In JS console:

var a = new Date(); 
var res = a.getUTCDay()+ '-' + a.getUTCMonth() + '-' + a.getUTCFullYear(); 
res;

The result is "3-11-2013", but the value of 'a' variable is "Wed, 04 Dec 2013 16:28:03 GMT"

What is wrong?

like image 968
krevedko Avatar asked Nov 23 '25 11:11

krevedko


2 Answers

What is wrong?

getUTCDay returns the day of the week, not the day of the month:

The getUTCDay() method returns the day of the week in the specified date according to universal time, where 0 represents Sunday.

getUTCMonth returns the month, 0 based:

The value returned by getUTCMonth is an integer between 0 and 11 corresponding to the month. 0 for January, 1 for February, 2 for March, and so on.

You want to use .getUTCDate instead and add +1 to the return value of .getUTCMonth:

var res = [a.getUTCDate(), a.getUTCMonth() + 1, a.getUTCFullYear()].join('-');
like image 165
Felix Kling Avatar answered Nov 25 '25 02:11

Felix Kling


The getUTCDay() and getUTCMonth() are both index based (starts with 0), you need to +1 theme to get the "real" value

like image 25
udidu Avatar answered Nov 25 '25 02:11

udidu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!