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

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

How to convert string to Date object?

javascriptjquery

提问by Bdfy

How to convert date string to Date object ?

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

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

回答by Verdi Erel Ergün

The best way to do this is using new Date()

最好的方法是使用 new Date()

Example:

例子:

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

回答by fmsf

Use jquery ui date parser.

使用 jquery ui 日期解析器。

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

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

This is the best function for parsing dates out of strings that I've had the pleasure to work with in js. And as you added the tag jquery it's probably the best solution for you.

这是从字符串中解析日期的最佳函数,我很高兴在 js 中使用它。当您添加标签 jquery 时,它可能是您的最佳解决方案。

回答by user2182143

I just wrote a javascript function that works for any date input field. I'm using jquery date picker and it works well with that.

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

hope it helps. Happy coding :)

希望能帮助到你。快乐编码:)