2009-12-24 69 views

回答

7

目前沒有跨瀏覽器的Date.format()方法。像Ext這樣的工具包有一個,但不是全部(我非常確定jQuery沒有)。如果你需要靈活性,你可以在網上找到幾種這樣的方法。如果你希望總是用那麼同樣的格式:Java的的SimpleDateFormat的格式方法

var now = new Date(); 
var pretty = [ 
    now.getFullYear(), 
    '-', 
    now.getMonth() + 1, 
    '-', 
    now.getDate(), 
    ' ', 
    now.getHours(), 
    ':', 
    now.getMinutes(), 
    ':', 
    now.getSeconds() 
].join(''); 
+0

仔細想想你是想在本地時間還是使用時區(或「Z」),還需要填充。 ES5提供了一個toISOString()方法,在今天的某些瀏覽器中可用。 – peller 2009-12-24 19:36:40

2
<script type="text/javascript"> 
    function formatDate(d){ 
    function pad(n){return n<10 ? '0'+n : n} 
    return [d.getUTCFullYear(),'-', 
      pad(d.getUTCMonth()+1),'-', 
      pad(d.getUTCDate()),' ', 
      pad(d.getUTCHours()),':', 
      pad(d.getUTCMinutes()),':', 
      pad(d.getUTCSeconds())].join(""); 
    } 

    var d = new Date(); 
    var formattedDate = formatDate(d); 
</script 
2

到日期格式

<script type="text/javascript"> 
<!-- 
var d = new Date(); 
var curr_date = d.getDate(); 
var curr_month = d.getMonth(); 
curr_month++; 
var curr_year = d.getFullYear(); 
document.write(curr_date + "-" + curr_month + "-" + curr_year); 
//--> 
</script> 

打印:24-12-2009

格式化時間,你可以做

<script type="text/javascript"> 
<!-- 

var d = new Date(); 
var curr_hour = d.getHours(); 
var curr_min = d.getMinutes(); 

var curr_sec = d.getSeconds(); 

document.write(curr_hour + ":" + curr_min + ":" 
+ curr_sec); 

//--> 
</script> 

打印:8點32分33秒

0

這裏是

一個不錯的

JavaScript (ActionScript) Date.format

,或者你可以使用這樣

var dt = new Date(); 

var timeString = dt.getFullYear() + "-" + dt.getMonth() + "-" + dt.getDate() + " " + dt.getHours() + ":" + dt.getMinutes() +":" + dt.getSeconds() 
0

使用日期的作品作爲發現​​here,格式化自己的喜好。

即。

var now = new Date(); 
var formatStr = now.getFullYear() + " - " + now.getMonth() + " - " + now.getDate(); 
// formatStr = "2009 - 12 - 23" 
相關問題