2010-02-23 11 views

回答

30

我會與你的意思是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

感謝您的答案,其實我的意思是Javascript時間戳。 javascript timestamp = unix timestamps * 1000 因爲javascript timestamp是自1月1日以來的秒數00:00:00 UTC – rmk 2010-02-23 01:17:58

+1

我對此進行了修改,其中包括添加年份,月份和日期。我遇到的兩個驚喜是你想要dt.getDate()而不是dt.getDay()(getDay返回星期幾);並且dt.getYear()在IE 6中返回我們通常認爲的年份(例如2011),但返回年份 - 在我測試的其他瀏覽器(Chrome,Opera,Firefox)中爲1900年。只是要注意的事情。 – 2011-07-08 20:27:29

5

這將顯示在您問(HH:MM:SS

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

簡短而甜美。謝謝! – 2014-01-15 23:40:52

+0

我得到更長的時間:20:07:30 GMT + 0100(中歐標準時間) – Jeffz 2017-11-29 19:05:22

30

這裏的格式顯示當前時間的一個函數,以UTC提供靈活的日期格式。它接受類似於Java的SimpleDateFormat的一個格式字符串:

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); 
     } 
    }); 
} 

你可以使用這樣的:

formatDate(new Date(timestamp), '%H:%m:%s'); 
相關問題