Javascript 在Javascript中将字符串转换为日期时间格式

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

convert string into datetime format in Javascript

javascriptstring-conversion

提问by dexter

i have a string which, i want to compare with a javascript datetime object. how to convert string "1/1/1912" into datetime using JavaScript so that i can compare like

我有一个字符串,我想与一个 javascript datetime 对象进行比较。如何使用 JavaScript 将字符串“1/1/1912”转换为日期时间,以便我可以比较

if (EDateTime > ('1/1/1912'))  {...}

回答by slashnick

You could do this simply with a split if you can guarantee the date format.

如果您可以保证日期格式,您可以简单地使用拆分来完成此操作。

var dateArray = '1/1/1912'.split("/");
new Date(dateArray[2], dateArray[1], dateArray[0]);

回答by Robert Kolman

        var dateArray = '2012-02-17 01:10:59'.split(' ');
        var year = dateArray[0].split('-');
        var time = dateArray[1].split(':');

        var finishDate = new Date(year[0], year[1], year[2], time[0], time[1], time[2])

回答by YOU

How about using DateJSlibrary?

使用DateJS库怎么样?

It can convert 1/1/1912to Monday, January 01, 1912 12:00:00 AMeasily

它可以轻松转换1/1/1912Monday, January 01, 1912 12:00:00 AM

回答by hsz

Convert your string to timestampwith Dateobject.

将您的字符串转换为timestampwithDate对象。

I found something like:

我发现了类似的东西:

function toTimestamp(year,month,day,hour,minute,second){
   var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
   return datum.getTime()/1000;
}

Year, monthand dayparts get with regular expressions.

Yearmonthday部分得到regular expressions