Javascript 将字符串转换为日期时间

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

Convert string to datetime

javascriptstringdatedatetimetype-conversion

提问by Damir

How to convert string like '01-01-1970 00:03:44'to datetime?

如何将字符串转换'01-01-1970 00:03:44'为日期时间?

采纳答案by KooiInc

For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date.

对于这种格式(假设 datepart 的格式为 dd-mm-yyyy),在纯 javascript 中使用dateString2Date.

[Edit] Added an ES6 utility method to parse a date string using a format string parameter (format) to inform the method about the position of date/month/year in the input string.

[编辑] 添加了一个 ES6 实用程序方法来使用格式字符串参数 ( format)来解析日期字符串,以通知该方法有关输入字符串中日期/月/年的位置。

var result = document.querySelector('#result');

result.textContent = 
  `*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${
    dateString2Date('01-01-2016 00:03:44')}`;

result.textContent += 
  `\n\n*With formatting\ntryParseDateFromString('01-01-2016 00:03:44', 'dmy'):\n => ${
  tryParseDateFromString('01-01-2016 00:03:44', "dmy").toUTCString()}`;

result.textContent += 
  `\n\nWith formatting\ntryParseDateFromString('03/01/2016', 'mdy'):\n => ${
  tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;

// fixed format dd-mm-yyyy
function dateString2Date(dateString) {
  var dt  = dateString.split(/\-|\s/);
  return new Date(dt.slice(0,3).reverse().join('-') + ' ' + dt[3]);
}

// multiple formats (e.g. yyyy/mm/dd or mm-dd-yyyy etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
  if (!dateStringCandidateValue) { return null; }
  let mapFormat = format
          .split("")
          .reduce(function (a, b, i) { a[b] = i; return a;}, {});
  const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);
  const datePart = dateStr2Array.slice(0, 3);
  let datePartFormatted = [
          +datePart[mapFormat.y],
          +datePart[mapFormat.m]-1,
          +datePart[mapFormat.d] ];
  if (dateStr2Array.length > 3) {
      dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));
  }
  // test date validity according to given [format]
  const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));
  return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&
         dateTrial.getMonth() === datePartFormatted[1] &&
         dateTrial.getDate() === datePartFormatted[2]
            ? dateTrial :
            null;
}
<pre id="result"></pre>

回答by Luke

Keep it simple with new Date(string). This should do it...

保持简单new Date(string)。这个应该可以...

var s = '01-01-1970 00:03:44';
var d = new Date(s);
console.log(d); // ---> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time)

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

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

回答by Michael Blake

http://www.w3schools.com/jsref/jsref_parse.asp

http://www.w3schools.com/jsref/jsref_parse.asp

    <script type="text/javascript">
        var d = Date.parse("Jul 8, 2005");
        document.write(d);<br>
    </script>

回答by Rhys Bradbury

You could use the moment.jslibrary.

您可以使用moment.js库。

Then simply:

然后简单地:

var stringDate = '01-01-1970 00:03:44';
var momentDateObj = moment(stringDate);

Checkout their api also, helps with formatting, adding, subtracting (days, months, years, other moment objects).

也检查他们的 api,有助于格式化、添加、减去(天、月、年、其他时刻对象)。

I hope this helps.

我希望这有帮助。

Rhys

里斯

回答by sameerfair

well, thought I should mention a solution I came across through some trying. Discovered whilst fixing a defect of someone comparing dates as strings.

好吧,我想我应该提到我通过一些尝试遇到的解决方案。在修复某人将日期作为字符串进行比较的缺陷时发现。

new Date(Date.parse('01-01-1970 01:03:44'))

新日期(Date.parse('01-01-1970 01:03:44'))

回答by user3086015

formatDateTime(sDate,FormatType) {
    var lDate = new Date(sDate)

    var month=new Array(12);
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";

    var weekday=new Array(7);
    weekday[0]="Sunday";
    weekday[1]="Monday";
    weekday[2]="Tuesday";
    weekday[3]="Wednesday";
    weekday[4]="Thursday";
    weekday[5]="Friday";
    weekday[6]="Saturday";

    var hh = lDate.getHours() < 10 ? '0' + 
        lDate.getHours() : lDate.getHours();
    var mi = lDate.getMinutes() < 10 ? '0' + 
        lDate.getMinutes() : lDate.getMinutes();
    var ss = lDate.getSeconds() < 10 ? '0' + 
        lDate.getSeconds() : lDate.getSeconds();

    var d = lDate.getDate();
    var dd = d < 10 ? '0' + d : d;
    var yyyy = lDate.getFullYear();
    var mon = eval(lDate.getMonth()+1);
    var mm = (mon<10?'0'+mon:mon);
    var monthName=month[lDate.getMonth()];
    var weekdayName=weekday[lDate.getDay()];

    if(FormatType==1) {
       return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi;
    } else if(FormatType==2) {
       return weekdayName+', '+monthName+' '+ 
            dd +', ' + yyyy;
    } else if(FormatType==3) {
       return mm+'/'+dd+'/'+yyyy; 
    } else if(FormatType==4) {
       var dd1 = lDate.getDate();    
       return dd1+'-'+Left(monthName,3)+'-'+yyyy;    
    } else if(FormatType==5) {
        return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi+':'+ss;
    } else if(FormatType == 6) {
        return mon + '/' + d + '/' + yyyy + ' ' + 
            hh + ':' + mi + ':' + ss;
    } else if(FormatType == 7) {
        return  dd + '-' + monthName.substring(0,3) + 
            '-' + yyyy + ' ' + hh + ':' + mi + ':' + ss;
    }
}

回答by insign

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

回答by Mile Mijatovi?

For this format (supposed datepart has the format dd-mm-yyyy) in plain javascript:

对于这种格式(假设日期部分的格式为 dd-mm-yyyy),在纯 javascript 中:

var dt  = '01-01-1970 00:03:44'.split(/\-|\s/)
    dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]);

回答by Nick

There aren't any built in ways, you might want to try something like this: see also this question

没有任何内置的方式,你可能想尝试像这样:又见这个问题