如何将字符串转换为Date对象?

时间:2011-10-16 14:48:55

标签: javascript jquery

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

2011-09-19T19:49:21+04:00

3 个答案:

答案 0 :(得分:22)

执行此操作的最佳方法是使用new Date()

示例:

var stringDate = '2011-09-19T19:49:21+04:00'
var date = new Date(stringDate) // Mon Sep 19 2011 08:49:21 GMT-0700 (PDT)

答案 1 :(得分:10)

使用jquery ui date parser。

http://docs.jquery.com/UI/Datepicker/parseDate

这是解析我喜欢在js中工作的字符串日期的最佳函数。当你添加标签jquery时,它可能是你的最佳解决方案。

答案 2 :(得分:3)

我刚写了一个适用于任何日期输入字段的javascript函数。我正在使用jquery日期选择器,它可以很好地使用它。

<!DOCTYPE html>
<html>
<body>

<p>Click the button to extract characters from the string.</p>

<button onclick="myFunction()">Try it</button>

<p id="enddate"></p>
<p id="startDate"></p>

<script>
  function myFunction() {
//var str = document.getElementById("start_date).value;
// var end = document.getElementById("end_date).value;

  var str = "2014-11-26";
  var end = "2014-11-22";


//first four strings (year) - starting from zero (first parameter), ends at 4th character (second parameter). It excludes the last character.
var year = str.substring(0,4);
var month = str.substring(5,7);//first two characters since 5th. It excludes the 7th character.
var date = str.substring(8,10);//first two character since 8th char. It excludes the 10th character.


var endYear = end.substring(0,4);
var endMonth = end.substring(5,7);
var endDate = end.substring(8,10);

var startDate = new Date(year, month-1, date);
var endDate = new Date(endYear, endMonth-1, endDate);

document.getElementById("enddate").HTML=endDate;
document.getElementById("startDate").HTML=startDate;


if (startDate > endDate) {
  alert('start date should be less than end date');
  return false;

} else {

 alert('date is ok..');
 return true;
}



}
 </script>

 </body>
 </html>
希望它有所帮助。快乐的编码:)