如何将字符串转换为JavaScript日期对象?

var st = "date in some format"
var dt = new Date();

var dt_st = // st in Date format, same as dt.

当前回答

将其作为参数传递给Date():

var st = "date in some format"
var dt = new Date(st);

您可以使用,例如:dt.getMonth()来访问日期、月、年。

其他回答

使用此格式....

//get current date in javascript

  var currentDate = new Date();


// for getting a date from a textbox as string format

   var newDate=document.getElementById("<%=textBox1.ClientID%>").value;

// convert this date to date time

   var MyDate = new Date(newDate);

转换为pt-BR格式:

    var dateString = "13/10/2014";
    var dataSplit = dateString.split('/');
    var dateConverted;

    if (dataSplit[2].split(" ").length > 1) {

        var hora = dataSplit[2].split(" ")[1].split(':');
        dataSplit[2] = dataSplit[2].split(" ")[0];
        dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);

    } else {
        dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
    }

我希望能帮助到别人!!

还有另一种方式:

String.prototype.toDate = function(format) {
    format = format || "dmy";
    var separator = this.match(/[^0-9]/)[0];
    var components = this.split(separator);
    var day, month, year;
    for (var key in format) {
        var fmt_value = format[key];
        var value = components[key];
        switch (fmt_value) {
            case "d":
                day = parseInt(value);
                break;
            case "m":
                month = parseInt(value)-1;
                break;
            case "y":
                year = parseInt(value);
        }
    }
    return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z

性能

今天(2020.05.08),我对所选解决方案进行了测试-有两种情况:输入日期是ISO8601字符串(Ad,Bd,Cd,Dd,Ed),输入日期是时间戳(At, Ct, Dt)。解决方案Bd,Cd,Ct不返回js Date对象作为结果,但我添加它们,因为它们可能是有用的,但我没有将它们与有效的解决方案进行比较。该结果对于大量数据解析非常有用。

结论

解决方案new Date (Ad)比moment.js (Dd)快50-100倍,适用于所有浏览器的ISO日期和时间戳 解决方案new Date (Ad)比parseDate (Ed)快10倍 解决方案date .parse(Bd)是最快的,如果我们需要在所有浏览器上从ISO日期获得时间戳

细节

我在MacOs High Sierra 10.13.6、Chrome 81.0、Safari 13.1、Firefox 75.0上进行测试。解决方案parseDate (Ed)使用新的Date(0)和手动设置UTC日期组件。

let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date let ts = +'1589328000000'; // timestamp let Ad = new Date(ds); let Bd = Date.parse(ds); let Cd = moment(ds); let Dd = moment(ds).toDate(); let Ed = parseDate(ds); let At = new Date(ts); let Ct = moment(ts); let Dt = moment(ts).toDate(); log = (n,d) => console.log(`${n}: ${+d} ${d}`); console.log('from date string:', ds) log('Ad', Ad); log('Bd', Bd); log('Cd', Cd); log('Dd', Dd); log('Ed', Ed); console.log('from timestamp:', ts) log('At', At); log('Ct', Ct); log('Dt', Dt); function parseDate(dateStr) { let [year,month,day] = dateStr.split(' ')[0].split('-'); let d=new Date(0); d.setUTCFullYear(year); d.setUTCMonth(month-1); d.setUTCDate(day) return d; } <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script> This snippet only presents used soultions

铬检测结果

对于那些正在寻找小巧而智能的解决方案的人:

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);
};

例子:

"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");