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

13

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

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

2
这个日期字符串是从哪里来的?如果是从服务器来的,你唯一安全的方法就是手动处理,因为每个国家对于日期和时间的格式可能都不同,你无法确定。 - Shadow The Spring Wizard
2
请查看此帖子:https://dev59.com/THRB5IYBdhLWcg3w4bOv - Annie Lagang
1
这与jquery有什么关系呢?因为你添加了那个标签? - tereško
3个回答

26
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)

12

使用jQuery UI日期解析器。

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

这是我在JavaScript中使用过的最佳字符串解析日期函数,并且由于您添加了jquery标签,它很可能是您的最佳解决方案。


2
日期选择器支持时间吗?例如,19:49:21+04:00 部分? - Adam
1
这个链接可能也会有用 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/parse - zabusa

2
我刚刚写了一个适用于任何日期输入字段的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>

希望这能有所帮助。愉快编码 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接