JavaScript 新日期()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5581854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript New Date()
提问by DAK
I have the following JavaScript code but for some reason time is not including minutes:
我有以下 JavaScript 代码,但由于某种原因,时间不包括分钟:
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:
当我使用 firebug 进行调试时,这些是我的价值:
$("#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
如您所见, timeUntil 设置为14:00:00
而不是14:20:00
回答by niksvp
parseInt(time)
is the problem
parseInt(time)
是问题
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);
回答by Justin Ethier
According to the Mozilla documentation for Date, the following constructors are supported:
根据Date的Mozilla 文档,支持以下构造函数:
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.
这意味着在您的构造函数中,当您传递 时parseInt(time)
,该参数仅用于该hour
参数。您需要为分钟传递一个单独的参数,如果您碰巧需要几秒钟,则需要传递另一个参数。
此外,您应该始终将
base
base
参数传递给parseInt
parseInt
,如下所示: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.
否则,当您解析带有0
诸如 之类的前导parseInt('08')
值时,该值将被解释为八进制数。
回答by davin
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 isto JS's Date
constructor, which will make life easier.
整个转换相当臃肿,我建议尝试以一种可以按原样传递给 JSDate
构造函数的格式来格式化字符串,这将使生活更轻松。
回答by Headshota
parseInt ("14:20:00")
returns 14
parseInt ("14:20:00")
返回 14