2013-04-10 12 views
6

Come ottengo il tempo dalla stringa della data utilizzando JavaScript.Ottenere il tempo da una stringa di data

mio DateString è nel seguente modo: 2013-04-08T10: 28: 43Z

Come dividere il tempo in ore e minuti formato. Voglio mostrare il flusso di attività nel modo seguente:

xxx ha aggiornato 2 ore fa
yyy ha aggiornato 3min fa

+2

Si può avere un'occhiata a questo Darshan

+0

http://www.w3schools.com/js/js_obj_date.asp - tutorial http://www.w3schools.com/jsref/jsref_obj_date.asp - JavaScript Data Riferimento oggetto – Viliam

+0

possibile duplicato di [javascript Data ISO8601] (http://stackoverflow.com/questions/6228302/javascript-date-iso8601) –

risposta

1

semplice Javascript è più che sufficiente: Date.parse convertirà la stringa a timestamp:

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

ma la data è nel formato di stringa ISO – vishnu

10

Basta creare nuovo Data oggetto:

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

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

Perché questo è downvoted? JavaScript supporta il formato ISO 8601 immediatamente. –

+0

@JACK GRAZIE! Finalmente qualcuno è ragionevole. – Stasel

+0

Sì, questo è esattamente giusto. anche var seconds = myDate.getSeconds(); – pollaris

1

Estrai una data dalla tua dataSt anello

primo estratto i numeri con

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

Quindi è possibile costruire un oggetto Date o saltare questo passaggio

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

E chiamare getHours e getMinutes su questo oggetto Date.

Se si salta questo, ottenere direttamente +sp[3] per ore e +sp[4] per minuti.


Calcola la differenza

Dal momento che ti sembra di avere da confrontare con la società, si otterrà differenza di tempo in questo modo:

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

E quindi chiamare getHours e getMinutes su timeDifference.

-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

Problemi correlati