2010-02-23 8 views

risposta

30

andrò con il presupposto che si intende timestamp Unix:

var formatTime = function(unixTimestamp) { 
    var dt = new Date(unixTimestamp * 1000); 

    var hours = dt.getHours(); 
    var minutes = dt.getMinutes(); 
    var seconds = dt.getSeconds(); 

    // the above dt.get...() functions return a single digit 
    // so I prepend the zero here when needed 
    if (hours < 10) 
    hours = '0' + hours; 

    if (minutes < 10) 
    minutes = '0' + minutes; 

    if (seconds < 10) 
    seconds = '0' + seconds; 

    return hours + ":" + minutes + ":" + seconds; 
}  

var formattedTime = formatTime(1266272460); 
document.write(formattedTime); 
+2

Grazie per la risposta, in realtà intendevo i timestamp di Javascript. javascript timestamp = unix timestamps * 1000 perché il timestamp javascript è il numero di ms dal 1 gennaio 1970 00:00:00 UTC – rmk

+1

L'ho modificato per i miei scopi, che includevano l'aggiunta di un anno, mese e giorno. Due sorprese che ho riscontrato sono che vuoi dt.getDate() invece di dt.getDay() (getDay restituisce il giorno della settimana); e che dt.getYear() restituisce ciò che normalmente pensiamo come l'anno (ad esempio, 2011) in IE 6, ma restituisce l'anno 1900 negli altri browser che ho testato (Chrome, Opera, Firefox). Solo qualcosa di cui essere a conoscenza. –

5

Ciò visualizzare l'ora corrente nel formato richiesto (HH:MM:SS)

function dostuff() 
{ 
var item = new Date(); 
alert(item.toTimeString()); 
} 
+0

Breve e dolce. Grazie! –

+0

Sto ricevendo qualcosa di più lungo: 20:07:30 GMT + 0100 (ora standard dell'Europa centrale) – Jeffz

30

Ecco una funzione che fornisce una formattazione flessibile di una data in UTC. Si accetta una stringa di formato simile a quello di SimpleDateFormat di Java:

function formatDate(date, fmt) { 
    function pad(value) { 
     return (value.toString().length < 2) ? '0' + value : value; 
    } 
    return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) { 
     switch (fmtCode) { 
     case 'Y': 
      return date.getUTCFullYear(); 
     case 'M': 
      return pad(date.getUTCMonth() + 1); 
     case 'd': 
      return pad(date.getUTCDate()); 
     case 'H': 
      return pad(date.getUTCHours()); 
     case 'm': 
      return pad(date.getUTCMinutes()); 
     case 's': 
      return pad(date.getUTCSeconds()); 
     default: 
      throw new Error('Unsupported format code: ' + fmtCode); 
     } 
    }); 
} 

si potrebbe usare in questo modo:

formatDate(new Date(timestamp), '%H:%m:%s'); 
Problemi correlati