Javascript 如何从javascript中的字符串创建日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8224459/
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
How to create a date object from string in javascript
提问by Bader
Having this string 30/11/2011
. I want to convert it to date object.
有了这个字符串30/11/2011
。我想将其转换为日期对象。
Do I need to use :
我是否需要使用:
Date d = new Date(2011,11,30); /* months 1..12? */
or
或者
Date d = new Date(2011,10,30); /* months 0..11? */
?
?
回答by Dogbert
var d = new Date(2011,10,30);
as months are indexed from 0 in js.
因为月份在 js 中从 0 开始索引。
回答by Igor Dymov
You definitely want to use the second expression since months in JS are enumerated from 0.
您肯定要使用第二个表达式,因为 JS 中的月份是从 0 开始枚举的。
Also you may use Date.parse method, but it uses different date format:
您也可以使用 Date.parse 方法,但它使用不同的日期格式:
var d = Date.parse("11/30/2011");
回答by Christopher Tokar
The syntax is as follows:
语法如下:
new Date(year, month [, day, hour, minute, second, millisecond ])
so
所以
Date d = new Date(2011,10,30);
is correct; day, hour, minute, second, millisecond are optional.
是正确的; 天、小时、分钟、秒、毫秒是可选的。
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
回答by Mayank
There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,
如上所述,有多种创建日期的方法。我不会重复同样的事情。如果这是您正在寻找的,这是在Java Script中将字符串转换为日期的小方法,
function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1 = parseInt(str1.substring(0,2));
var mon1 = parseInt(str1.substring(3,5));
var yr1 = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}
回答by Pearl
Very simple:
很简单:
var dt=new Date("2011/11/30");
Date should be in ISO format yyyy/MM/dd.
日期应采用 ISO 格式 yyyy/MM/dd。
回答by pashaplus
First extract the string like this
首先像这样提取字符串
var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
Then,
然后,
var d = new Date( dateString[3], dateString[2]-1, dateString[1] );
回答by Sune Rasmussen
Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.
一直以来,有关将在实际JavaScript的规范的任何问题,我会强烈建议在Mozilla开发者网络,以及他们的JavaScript基准。
As it states in the topic of the Date objectabout the argument variant you use:
正如它在Date 对象的主题中关于您使用的参数变体所述:
new Date(year, month, day [, hour, minute, second, millisecond ])
And about the months parameter:
关于月参数:
monthInteger value representing the month, beginning with 0 for January to 11 for December.
month表示月份的整数值,从 0 开始表示 1 月到 11 表示 12 月。
Clearly, then, you should use the month number 10 for November.
很明显,您应该将月份编号 10 用于 11 月。
P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.
PS:之所以推荐MDN,是因为它的正确性,很好的解释,例子,浏览器兼容性图表。
回答by Gerard ONeill
I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)
我不敢相信 javascript 与解析日期不一致。而且我听到没有时区时的默认设置将从 UTC 更改为本地 - 希望网络已准备就绪 ;)
I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).
在解析日期时,我更喜欢让 Javascript 做繁重的工作。但是,以相当透明的方式处理本地时区问题会很好。考虑到这两点,这里有一个函数可以在当前状态下完成它——当 Javascript 发生变化时,它仍然可以工作,但随后可以被删除(有一点时间让人们赶上旧浏览器/nodejs当然)。
function strToDate(dateStr)
{
var dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);
if (!tz)
{
var newTzOffset = dateTry.getTimezoneOffset() / 60;
var newSignStr = (newTzOffset >= 0) ? '-' : '+';
var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';
dateStr = dateStr.trim() + newTz;
dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
}
return dateTry;
}
We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).
无论如何,我们都需要一个日期对象;所以创建一个。如果有时区,我们就完成了。否则,使用 +hh:mm 格式(比 +hhmm 更容易接受)创建本地时区字符串。