How do you set a strftime with javascript?

旧城冷巷雨未停 提交于 2021-02-04 14:25:22

问题


I need to custom format dates. In ruby, I would use strftime, or string formatted time, to accomplish this.

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

Does javascript use strftime or some equivalent? How can I get a similar effect in javascript?


回答1:


UPDATE

Arguments of toLocaleString method can also configure the format of the dates. This is supported in modern browser versions, you can see more information here.

let date = new Date(Date.UTC(2015, 5, 27, 12, 0, 0))
, options = {weekday: 'short', month: 'short', day: 'numeric' };
console.log(date.toLocaleString('es-ES', options)); //sáb. 27 de jun.

In JavaScript there are methods to create dates, but no native code to format. You can read about Date(). But there are libraries that do. Particularly for me the best library to use it deeply is MomentJS. So you can do something like as: moment().format('dd, d of MMMM')

However, if you do not want to use a library you have access to the following native Date properties:

var now = new Date();

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

Date Object some properties

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



回答2:


There are a couple of good strftime() ports for javascript.

https://github.com/samsonjs/strftime is very comprehensive and a lot of specifiers from C-lang and Ruby have been ported.

https://thdoan.github.io/strftime/ is simpler if you're looking for something lite.

I appreciate Walter's very detailed and clear answer about custom implementation, but I personally wouldn't want to write code on my own for common things like date formatting(I actually came back to using libs above after seeing repeated issues with custom code).



来源:https://stackoverflow.com/questions/31089749/how-do-you-set-a-strftime-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!