2015-06-27 15 views
9

Tôi cần ngày định dạng tùy chỉnh. Trong ruby, tôi sẽ sử dụng strftime, hoặc chuỗi định dạng thời gian, để thực hiện điều này.Làm thế nào để bạn thiết lập một strftime với javascript?

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

javascript có sử dụng strftime hoặc một số tương đương không? Làm thế nào tôi có thể có được một hiệu ứng tương tự trong javascript?

+0

MomentJ đã giới thiệu mã thông báo định dạng mới trong phiên bản 2.0 và hỗ trợ nhiều ngôn ngữ rmating [documented here] (https://gist.github.com/timrwood/e72f2eef320ed9e37c51) –

Trả lời

9

Trong JavaScript có các phương pháp để tạo ngày, nhưng không có mã gốc để định dạng. Bạn có thể đọc khoảng Date(). Nhưng có libraries. Đặc biệt đối với tôi, thư viện tốt nhất để sử dụng nó là MomentJS. Vì vậy, bạn có thể làm điều gì đó như là: moment().format('dd, d of MMMM')

Tuy nhiên, nếu bạn không muốn sử dụng một thư viện bạn có quyền truy cập vào các tính chất ngày mẹ đẻ sau:

var now = new Date(); 
 

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

Date Object một số đặc tính

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 
Các vấn đề liên quan