我正在制作一个类似于PHP的JavaScript mkDate函数,并且我已经得到了正确的日期,但它比预期的要短5个小时。我一直盯着这看了一个小时。这是我的代码:
function mkDate(hour, minute, second, month, day, year)
{
month--;
var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if(new Date(year, 1, 29, 0, 0).getMonth() != 2) { monthDays[1] = 29; }
var years = year - 1970;
var leapYears = parseInt((year - 1972)/4);
var days = (years - leapYears) * 365;
days += leapYears * 366;
for(var i = 0; i < month; i++) {
days += monthDays[i];
}
days += day;
var time = days * 60 * 60 * 24 * 1000;
time += hour * 60 * 60 * 1000;
time += minute * 60 * 1000;
time += second * 1000;
var tDate = new Date();
tDate.setTime(time);
return tDate;
}
var myDate = mkDate(16, 38, 23, 7, 10, 2013);
// myDate should be Wednesday, July 10, 2013 04:38:23 PM
// but myDate is coming up with Wednesday, July 10, 2013 11:38:23 AM
答案 0 :(得分:10)
时区问题:settime takes milliseconds since midnight 01 January, 1970 UTC as an argument,您可以在当地时间投放。你在CDT,这是UTC以西5小时。
现在,Date has a constructor which takes exactly the fields you're feeding mkDate(但是以另一种顺序),所以你的功能可以简化为
function mkDate(hour, minute, second, month, day, year)
{
return new Date(year,month-1,day,hour, minute, second);
}
该日期将在当地时间。
编辑:我错过了月份字段中1的减法 - 至少有一个由Java和Javascript共享的错误....
答案 1 :(得分:1)
为什么不直接使用Date自己的构造函数,如果您的输入应该是 UTC 时间,可能使用Date.UTC
。这意味着本机功能可以为您完成所有工作。
function mkDate(hour, minute, second, month, day, year) {
return new Date(Date.UTC(year, month - 1, day, hour, minute));
}
mkDate(16, 38, 23, 7, 10, 2013);
// Wed Jul 10 2013 17:38:00 GMT+0100 (GMT Daylight Time)
如果您想在 UTC / GMT 中使用Date.prototype.toUTCString
或{{3}查看 UTC ,请在默认情况下以当地时间显示日期 }