admin管理员组文章数量:1398758
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?
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?
Share Improve this question edited Dec 4, 2013 at 16:36 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Dec 4, 2013 at 16:35 krevedkokrevedko 4,2631 gold badge20 silver badges13 bronze badges 3- 3 Months are zero based, and it seems you're missing a month and a day – adeneo Commented Dec 4, 2013 at 16:37
-
2
You are getting confused.
a.getUTCDay()
is day of the week. Not the date. – karthikr Commented Dec 4, 2013 at 16:39 -
1
Always read the documentation before you are using a method: developer.mozilla/en-US/docs/Web/JavaScript/Reference/…. It explains what
getUTCDay
andgetUTCMonth
return. – Felix Kling Commented Dec 4, 2013 at 16:41
3 Answers
Reset to default 7What 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('-');
The getUTCDay()
and getUTCMonth()
are both index based (starts with 0), you need to +1 theme to get the "real" value
Unless your codebase is very small, I would refrain from using these poor native JS date formatting functions and just import Moment.js.
本文标签: javascriptJS wrong UTC timeStack Overflow
版权声明:本文标题:javascript - JS: wrong UTC time - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744719050a2621584.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论