2011-07-11 49 views
0

我使用JavaScript以及Date.js,並且需要翻譯時間的字符串表示形式。Javascript以特定格式寫入時間

我開始用這種格式的時間:

 
3:00am 
2:30pm 
11:00am 

...並需要把他們的格式如下:

 
03:00:00 
14:00:00 
11:00:00 

我想用Date.parse開始的( ),然後打印小時,分鐘和秒鐘。但想知道是否有一個更優雅的方式來做到這一點,如沿線Date.format("HH:MM:SS")

什麼是一個好辦法做到這一點?

謝謝!

編輯::::

看起來你可以使用格式說明與Date.js:http://code.google.com/p/datejs/wiki/FormatSpecifiers

Date.parse("3:00am").toString("HH:mm:ss"); 
+0

你得到它與解析工作哦!好一個。我只能用parseExact來做。你是在自問自答。 –

+1

我在下載錯誤版本的Date.js時遇到了問題。你必須通過這個不在主站點上的特定區域下載它才能獲得最新版本:http://datejs.googlecode.com/svn/trunk/build/date-en-US.js –

回答

1

我相信這是回答OP正在尋找。 :-)

<html> 
    <head> 
    <title>Show US Times in 24h form with Date.js</title> 
    </head> 
    <body> 
    <script type="text/javascript" src="date.js"></script> 
    <script> 
     var d = Date.parseExact("2:30pm", "h:mmtt"); 
     document.write(d.toString("HH:mm:ss")); 
    </script> 
    </body> 
</html> 
的格式說明這裏

信息:http://code.google.com/p/datejs/wiki/FormatSpecifiers

3

The answer to all your questions

<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> 
+0

這是否返回小時和分鐘總是使用字符? (「02」而不是「2」) –

+1

這不使用Date.js,也不解析原始字符串,也不填充單位數的分鐘和秒。 –

+1

但它清楚地說明了如何做到這一點。從這裏開始,很容易繼續添加一些功能,以便在需要時添加前導零,例如... if(curr_min <10){curr_min ='0'+ curr_min; }'等 – Jules