Javascript 将字符串转换为 ISODate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35959853/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:25:59  来源:igfitidea点击:

Convert string to ISODate

javascriptdate

提问by user1665355

How could I convert the string "2015-02-02"to ISODate 2015-02-02T00:00:00.000Z? I was trying to find some example but did not.

如何将字符串转换"2015-02-02"为 ISODate 2015-02-02T00:00:00.000Z?我试图找到一些例子,但没有。

回答by Matthijs Brouns

You can use the regular Javascript date functionality for this

您可以为此使用常规的 Javascript 日期功能

new Date(dateString).toISOString()

from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

However, date parsing is very inconsistent across browsers so if you need this to be robust I would look into parsing using for example with Moment.js as this will allow you to specify a format string by which the date should be parsed like such

然而,日期解析在浏览器之间非常不一致,所以如果你需要它是健壮的,我会考虑使用例如 Moment.js 进行解析,因为这将允许你指定一个格式字符串,日期应该像这样解析

date = moment("12-25-1995", "YYYY-MM-DD");
date.format(); //will return an ISO representation of the date

from: http://momentjs.com/docs/#/parsing/string/

来自:http: //momentjs.com/docs/#/parsing/string/

回答by RobG

To change "2015-02-02" to "2015-02-02T00:00:00.000Z" simply append "T00:00:00.000Z":

要将“2015-02-02”更改为“2015-02-02T00:00:00.000Z”,只需附加“T00:00:00.000Z”:

console.log('2015-02-02' + 'T00:00:00.000Z');

Parsing to a Date and calling toISOStringwill fail in browsers that don't correctly parse ISO dates and those that don't have toISOString.

在无法正确解析 ISO 日期和没有toISOString 的浏览器中,解析为日期并调用toISOString将失败。

回答by lilhamad

new Date("11/11/2019").toISOString()

or use it as a variable

或将其用作变量

mydate = "11/11/2019"
new Date("11/11/2019").toISOString()

回答by Alex R

new Date("2015-02-02").toISOString()

回答by Vadorequest

new Date('2015-02-02').toISOString() // Results in "2015-02-02T00:00:00.000Z"

See this link for further documentation: http://www.w3schools.com/jsref/jsref_toisostring.asp

有关更多文档,请参阅此链接:http: //www.w3schools.com/jsref/jsref_toisostring.asp