2015-06-27 101 views
9

我需要自定義格式日期。在ruby中,我會使用strftime或字符串格式化的時間來完成此操作。你怎麼用javascript設置strftime?

now = Time.new 
now.strftime '%a, %d of %b' #=> "Sat, 27 of Jun" 

javascript是否使用strftime或一些等效?我怎樣才能在JavaScript中獲得類似的效果?

+0

MomentJs在2.0版本中引入了新的格式化標記,並且支持多種語言fo rmating [記錄在這裏](https://gist.github.com/timrwood/e72f2eef320ed9e37c51) –

回答

9

在JavaScript中有創建日期的方法,但沒有格式化的本地代碼。你可以閱讀關於Date()。但有libraries這樣做。特別是對我來說,深度使用它的最好的庫是MomentJS。所以,你可以這樣做的:moment().format('dd, d of MMMM')

但是,如果你不想使用庫,您可以訪問以下本機日期屬性:

var now = new Date(); 
 

 
document.write(now.toUTCString() + "<br>") 
 
document.write(now.toTimeString() + "<br>")

Date Object一些屬性

toDateString() Converts the date portion of a Date object into a readable string 
toGMTString() Deprecated. Use the toUTCString() method instead 
toISOString() Returns the date as a string, using the ISO standard 
toJSON() Returns the date as a string, formatted as a JSON date 
toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions 
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions 
toLocaleString() Converts a Date object to a string, using locale conventions 
toString() Converts a Date object to a string 
toTimeString() Converts the time portion of a Date object to a string 
toUTCString() Converts a Date object to a string, according to universal time