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

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

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

当前回答

var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));

输出将是:

dt => Date {Fri Apr 26 2013}

其他回答

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

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

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

Var a = "13:15" var b = toDate(a, "h:m") / /警报(b); document . write (b); 函数toDate(dStr, format) { var now = new Date(); If (format == "h:m") { now.setHours(下游。substr (0, dStr.indexOf(“:”))); now.setMinutes(dStr.substr(dStr.indexOf(":") + 1)); now.setSeconds (0); 现在返回; 其他} 返回“格式无效”; }

如果在转换为Date格式之前需要检查字符串的内容:

// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
  var d = mdy.split(/[\/\-\.]/, 3);

  if (d.length != 3) return null;

  // Check if date is valid
  var mon = parseInt(d[0]), 
      day = parseInt(d[1]),
      year= parseInt(d[2]);
  if (d[2].length == 2) year += 2000;
  if (day <= 31 && mon <= 12 && year >= 2015)
    return new Date(year, mon - 1, day);

  return null; 
}
                //little bit of code for Converting dates 

                var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

使用此格式....

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