在 JavaScript 中将字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5619202/
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
Converting a string to a date in JavaScript
提问by jslearner
How can I convert a string to a date in JavaScript?
如何在 JavaScript 中将字符串转换为日期?
var st = "date in some format"
var dt = new date();
var dt_st= //st in date format same as dt
回答by Pavel Hodek
The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
字符串解析的最佳字符串格式是日期 ISO 格式以及 JavaScript 日期对象构造函数。
Examples of ISO format: YYYY-MM-DD
or YYYY-MM-DDTHH:MM:SS
.
ISO 格式示例:YYYY-MM-DD
或YYYY-MM-DDTHH:MM:SS
.
But wait!Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.
可是等等!仅使用“ISO 格式”本身并不能可靠地工作。字符串有时被解析为 UTC,有时被解析为本地时间(基于浏览器供应商和版本)。最佳做法应该始终是将日期存储为 UTC,并以 UTC 进行计算。
To parse a date as UTC, append a Z- e.g.: new Date('2011-04-11T10:20:30Z')
.
要将日期解析为 UTC,请附加Z- 例如:new Date('2011-04-11T10:20:30Z')
。
To display a date in UTC, use .toUTCString()
,
to display a date in user's local time, use .toString()
.
要以 UTC 显示日期,请使用.toUTCString()
,
要以用户本地时间显示日期,请使用.toString()
。
More info on MDN | Dateand this answer.
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00')
. Note that the number of the month must be 1 less.
对于旧的 Internet Explorer 兼容性(小于 9 的 IE 版本不支持 Date 构造函数中的 ISO 格式),您应该将日期时间字符串表示拆分为它的部分,然后您可以使用使用日期时间部分的构造函数,例如: new Date('2011', '04' - 1, '11', '11', '51', '00')
. 请注意,月份数必须少 1。
Alternate method - use an appropriate library:
替代方法 - 使用适当的库:
You can also take advantage of the library Moment.jsthat allows parsing date with the specified time zone.
您还可以利用Moment.js库来解析指定时区的日期。
回答by Roman Podlinov
Unfortunately I found out that
不幸的是我发现
var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());
returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.
返回“2014 年 4 月 2 日星期三”。我知道这听起来很疯狂,但它发生在某些用户身上。
The bulletproof solutionis the following:
该防弹解决方案如下:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
回答by serega386
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'--'));
And the output will be:
输出将是:
dt => Date {Fri Apr 26 2013}
回答by Kassem
function stringToDate(_date,_format,_delimiter)
{
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
回答by Juan Caicedo
moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.
moment.js ( http://momentjs.com/) 是一个完整的使用日期包并且支持ISO 8601 字符串。
You could add a string date and format.
您可以添加字符串日期和格式。
moment("12-25-1995", "MM-DD-YYYY");
And you could check if a date is valid.
您可以检查日期是否有效。
moment("not a real date").isValid(); //Returns false
Some display examples
一些显示示例
let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL'))
// output: "3 months ago | February 1, 2019"
See documentation http://momentjs.com/docs/#/parsing/string-format/
请参阅文档 http://momentjs.com/docs/#/parsing/string-format/
Recommendation:I recommend to use a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily date from a simple string to date but I think that is a hard work to support all formats and variations of dates.
建议:我建议使用包含很多格式的日期的包,因为时区和格式时间管理确实是一个大问题,moment js解决了很多格式。您可以轻松地从一个简单的字符串解析日期,但我认为支持所有格式和日期变体是一项艰巨的工作。
回答by oblig
Pass it as an argument to Date():
将其作为参数传递给 Date():
var st = "date in some format"
var dt = new Date(st);
You can access the date, month, year using, for example: dt.getMonth()
.
您可以使用例如: 访问日期、月份、年份dt.getMonth()
。
回答by H6.
回答by Torsten Becker
new Date(2000, 10, 1)
will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"
new Date(2000, 10, 1)
会给你“2000 年 11 月 1 日星期三 00:00:00 GMT+0100 (CET)”
See that 0 for month gives you January
看到月份的 0 给你一月
回答by Arivan Bastos
For those who are looking for a tiny and smart solution:
对于那些正在寻找一个小巧而智能的解决方案的人:
String.prototype.toDate = function(format)
{
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds();
return new Date(year,month,day,hour,minute,second);
};
Example:
例子:
"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");