2011-10-16 38 views
9

如何將日期字符串轉換爲Date對象?如何將字符串轉換爲Date對象?

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

這個日期字符串來自哪裏?如果來自服務器,您唯一的安全方法是手動完成,因爲每個國家的日期和時間格式可能不同,您無法確定。 –

+2

檢查這個職位:http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript –

+1

這究竟與'jquery' ,因爲你已經添加了該標籤? –

回答

10

使用jquery ui日期解析器。

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

這是解析日期的是,我有幸在JS與工作串的最佳功能。而當你添加標籤jQuery它可能是你最好的解決方案。

+2

Datepicker的支持時間?即19:49:21 + 04:00部分?? – Adam

+1

此鏈接可能也有用 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse – zabusa

20

要做到這一點,最好的辦法是使用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) 
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> 

希望它有幫助。快樂編碼:)