如何使用 javascript 设置 strftime?

How do you set a strftime with javascript?

我需要自定义格式日期。在 ruby 中,我会使用 strftime 或字符串格式化时间来完成此操作。

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

javascript 是否使用 strftime 或类似的东西?我怎样才能在 javascript 中获得类似的效果?

更新

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.

JavaScript 中有创建日期的方法,但没有格式化的本机代码。您可以阅读有关 Date(). But there are libraries that do. Particularly for me the best library to use it deeply is MomentJS 的信息。所以你可以这样做:moment().format('dd, d of MMMM')

但是,如果您不想使用库,您可以访问以下本机 Date 属性:

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

有几个很好的 strftime() 移植 javascript。

https://github.com/samsonjs/strftime 非常全面,移植了很多来自 C-lang 和 Ruby 的说明符。

https://thdoan.github.io/strftime/ 如果您正在寻找精简版,则更简单。

我很欣赏 Walter 关于自定义实现的非常详细和明确的回答,但我个人不想自己编写代码来处理诸如日期格式之类的常见问题(在看到重复的问题后,我实际上又回到了使用上面的库自定义代码)。