admin管理员组文章数量:1396858
code like this
var date = new Date("2012/09/04");
console.log(date.getUTCDate());
//returns 3
can someone tell me how to get the correct date based on a time string like yyyy/mm/dd?
thx~
code like this
var date = new Date("2012/09/04");
console.log(date.getUTCDate());
//returns 3
can someone tell me how to get the correct date based on a time string like yyyy/mm/dd?
thx~
Share Improve this question asked Aug 4, 2012 at 3:10 vikingmutevikingmute 4122 gold badges10 silver badges25 bronze badges 1- expecting 4 when i give a string pattern like "2012/9/4" – vikingmute Commented Aug 4, 2012 at 3:34
2 Answers
Reset to default 7You shouldn't use getUTCxxx
if you're dealing only with dates (i.e. you're not concerned about time). If you create a Date
object like you did (specifying only the date) it will set the time to 0:00:00
. When converting to UTC, if your timezone is positive it will subtract some time from your date, so your date will represent the previous day.
Instead, I'd suggest just using getDate
for that.
Note: in my machine (I'm at UTC-3) the snippet above runs just fine (i.e. it returns 4
), but that's because new Date("2012/09/04")
here evaluates at:
alert(new Date("2012/09/04"));
// Tue Sep 04 2012 00:00:00 GMT-0300 (Hora oficial do Brasil)
alert(new Date("2012/09/04").toUTCString());
// Tue, 04 Sep 2012 03:00:00 GMT
If I were at, say, UTC+3 instead, I'd probably get results like:
alert(new Date("2012/09/04"));
// Tue Sep 04 2012 00:00:00 GMT+0300
alert(new Date("2012/09/04").toUTCString());
// Mon, 03 Sep 2012 21:00:00 GMT
Just tack on "UTC"
to the end of your string when you pass it to the constructor:
function UTCDate(s) {
return new Date(s + " UTC");
}
本文标签: datetimeJavascript getUTCDate return the previous dayStack Overflow
版权声明:本文标题:datetime - Javascript getUTCDate return the previous day - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744143247a2592714.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论