你如何用javascript设置strftime?

wil*_*des 16 javascript time date strftime

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

now = Time.new
now.strftime '%a, %d of %b' #=> "Sat, 27 of Jun"
Run Code Online (Sandbox Code Playgroud)

javascript使用strftime还是等效的?如何在javascript中获得类似的效果?

Wal*_*anG 13

UPDATE

toLocaleString方法的参数也可以配置日期的格式.现代浏览器版本支持此功能,您可以在此处查看更多信息.

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.
Run Code Online (Sandbox Code Playgroud)

在JavaScript中有创建日期的方法,但没有要格式化的本机代码.你可以阅读Date().但是有些图书馆可以做到.特别是对我来说,最好的图书馆使用它是MomentJS.所以你可以这样做:moment().format('dd, d of MMMM')

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

var now = new Date();

document.write(now.toUTCString() + "<br>")
document.write(now.toTimeString() + "<br>")
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)


Pra*_*lla 8

JavaScript 有几个很好的 strftime() 端口。

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

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

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

  • 我喜欢 https://thdoan.github.io/strftime/ 的轻盈和优雅!谢谢。 (3认同)