开发者

JavaScript New Date()

I have the following JavaScript code but for some reason开发者_JAVA百科 time is not including minutes:

var austDay = $("#<%= hiddenFieldTime.ClientID %>").val().split(" ");

var year = austDay[0];

var months = austDay[1];

var days = austDay[2];

var time = austDay[3];

var timeUntil = new Date(parseInt(year), parseInt(months), 
                         parseInt(days), parseInt(time));

When I debug using firebug these are my value:

$("#ctl00_hiddenFieldTime").val() = "2011, 5, 6, 14:20:00"

year = "2011,"

months = "5,"

days = "6,"

time = "14:20:00"

timeUntil = Date {Mon Jun 06 2011 14:00:00 GMT-0400 (Eastern Daylight Time)}

As you can see, timeUntil is set to 14:00:00 instead of 14:20:00


parseInt(time) is the problem

Here are the few dates initialization format

var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);


According to the Mozilla documentation for Date, the following constructors are supported:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])

This means that in your constructor, when you pass parseInt(time), that parameter is only used for the hour parameter. You need to pass a separate parameter for minutes, and yet another one if you happen to want seconds.


Also, you should always pass a base parameter to parseInt, like so:

parseInt(hours, 10)

Otherwise when you go to parse a value with a leading 0 such as parseInt('08'), the value will be interpreted as an octal number.


Your last conversion is going to drop everything after the colon:

parseInt("14:20:00"); // 14

The whole conversion is rather bloated, I suggest trying to format the string initially in a format you can pass as is to JS's Date constructor, which will make life easier.


parseInt ("14:20:00") returns 14

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜