2015-06-27 5 views
9

Ich muss Daten formatieren. In Ruby würde ich strftime oder string-formatierte Zeit verwenden, um dies zu erreichen.Wie stellen Sie eine strftime mit Javascript ein?

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

Verwendet Javascript strftime oder ein Äquivalent? Wie kann ich einen ähnlichen Effekt in Javascript bekommen?

+0

MomentJs führte neue Formatierungstoken in Version 2.0 ein und unterstützt viele Sprachen fo rmating [dokumentiert hier] (https://gist.github.com/timrwood/e72f2eef320ed9e37c51) –

Antwort

9

In JavaScript gibt es Methoden zum Erstellen von Daten, aber keinen systemeigenen Code zum Formatieren. Sie können über Date() lesen. Aber es gibt libraries, die tun. Besonders für mich ist die beste Bibliothek, um es tief zu verwenden, MomentJS. So können Sie etwas tun, wie zum Beispiel: moment().format('dd, d of MMMM')

Wenn Sie jedoch wollen nicht eine Bibliothek verwenden Sie haben Zugriff auf die folgenden nativen Datum Eigenschaften:

var now = new Date(); 
 

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

Date Object einige Eigenschaften

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 
Verwandte Themen