我需要自定义日期格式。在 ruby 中,我将使用 strftime(或字符串格式时间)来完成此操作。
now = Time.new
now.strftime '%a, %d of %b' #=> "Sat, 27 of Jun"
javascript 是否使用 strftime 或类似的东西?如何在 javascript 中获得类似的效果?
更新
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')
但是,如果您不想使用库,则可以访问以下本机日期属性:
var now = new Date();
document.write(now.toUTCString() + "<br>")
document.write(now.toTimeString() + "<br>")
以下是一些 Date 对象 属性:
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
有几个很好的 javascript 的 strftime() 端口。
https://github.com/samsonjs/strftime非常全面,并且移植了很多来自C-lang和Ruby的说明符。
https://thdoan.github.io/strftime/ 如果您正在寻找精简版的东西,则更简单。
我很欣赏沃尔特关于自定义实现的非常详细和清晰的答案,但我个人不想为诸如日期格式之类的常见问题自己编写代码(实际上,在看到自定义代码的重复问题后,我又回到了使用上面的库)。