2013-04-10 192 views
6

如何從使用JavaScript的日期字符串中獲取時間。從日期字符串獲取時間

我datestring是通過以下方式:2013-04-08T10:28:43Z

如何分割小時和分鐘格式的時間。我想說明的活動流按以下方式:

XXX已經更新2小時前
YYY已經更新了3分鐘前

+2

你可以看看這個 Darshan 2013-04-10 06:45:35

+0

http://www.w3schools.com/js/js_obj_date.asp - 教程 http://www.w3schools.com/jsref/jsref_obj_date.asp - javascript日期對象引用 – Viliam 2013-04-10 07:11:58

+0

[JavaScript的日期ISO8601]的可能重複( http://stackoverflow.com/questions/6228302/javascript-date-iso8601) – 2013-04-10 07:31:44

回答

1

簡單的JavaScript是綽綽有餘: Date.parse將您的字符串轉換爲時間戳:

var date_string = '2013-04-08T10:28:43Z'; 

var your_date_object = new Date(); 
your_date_object.setTime(Date.parse(date_string)); 

var min = your_date_object.getUTCMinutes(); 
var hour = your_date_object.getUTCHours(); 
+0

但日期是ISO字符串格式 – vishnu 2013-04-10 06:56:58

10

只需創建新的Date對象:

var myDate = new Date("2013-04-08T10:28:43Z"); 

var minutes = myDate.getMinutes(); 
var hours = myDate.getHours(); 
+2

爲什麼這是downvoted? JavaScript支持ISO 8601格式。 – 2013-04-10 07:36:14

+0

@Jack謝謝!最後有人合理。 – Stasel 2013-04-10 08:03:21

+0

是的,這是完全正確的。另外var seconds = myDate.getSeconds(); – pollaris 2017-08-30 15:33:10

1

從dateSt中提取一個日期環

先提取數字與

var sp = dateString.match(/\d+/g) 

然後你就可以建立一個Date對象或跳過此步驟

var dateObject = new Date(+sp[0], +sp[1]-1, +sp[2], +sp[3], +sp[4], +sp[5]) 

並調用getHoursgetMinutes此Date對象上。

如果你跳過這個,然後直接得到+sp[3]小時和+sp[4]分鐘。


計算的差異

既然你似乎與現在比較,你會得到的時間差是這樣的:

var timeDifference = new Date(new Date - dateObject); 

然後調用getHoursgetMinutestimeDifference

-1
var curr_date = new Date(); 
var test_date = new Date("2016-01-08 10:55:43"); 

hours_diff=Math.abs(test_date.getHours()-curr_date.getHours()); 
minutes_diff=Math.abs(test_date.getHours()*60+test_date.getMinutes()-curr_date.getHours()*60-curr_date.getMinutes()); 
console.log("xxx has updated "+hours_diff+" hours ago"); 
console.log("xxx has updated "+minutes_diff+" minutes ago"); //not so beautiful 

///STILL IF THE date is a string and !!NOT CREATED with DATE 
/// "Get the time from a date string" might have this solution 

var date = "2016-01-08 10:55:43"; 
var hours = date.slice(-8); 

console.log("hours and minutes string is "+hours); 

fiddle test