如何使用JavaScript设置strftime?

27

我需要自定义日期格式。在Ruby中,我会使用strftime或字符串格式化时间来实现此目的。

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

JavaScript使用strftime或其等效函数吗?我该如何在JavaScript中获得类似的效果?


MomentJs在2.0版本中引入了新的格式化标记,并支持许多语言格式在此处记录 - Glaubule
2个回答

29

更新

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.

在 JavaScript 中有创建日期的方法,但没有原生代码来格式化日期。你可以阅读关于 Date() 的信息。但是,有一些可以做到这一点。对我来说,最好的库是 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

8

有几个适用于JavaScript的strftime()端口很不错。

https://github.com/samsonjs/strftime非常全面,已经移植了许多来自C语言和Ruby的特定符号。

https://thdoan.github.io/strftime/如果你想要一个轻量级的东西,那么它更简单。

我很欣赏Walter关于自定义实现的非常详细和清晰的回答,但对于像日期格式化这样的常见事情,我个人不想编写自己的代码(在看到自定义代码重复问题后,我实际上又回到了上述库中)。


3
我喜欢https://thdoan.github.io/strftime/ 的轻盈和优雅!谢谢。 - Yuriy Ershov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接