简体   繁体   English

在Javascript中将日期转换为字符串

[英]Convert a date to string in Javascript

I'm looking for a way to convert a Javascript Date object to a string. 我正在寻找一种方法将Javascript Date对象转换为字符串。 I'm converting my site from Ruby to server side Javascript, and I'm looking for something analogous to strftime in Ruby, C, and many other languages. 我正在将我的网站从Ruby转换为服务器端Javascript,我正在寻找类似于Ruby,C和许多其他语言的strftime东西。

I found plenty of simple scripts that do this kind of conversion, but I'd prefer not to include a custom implementation if there is a standard way of doing this. 我发现有很多简单的脚本可以进行这种转换,但是如果有一种标准的方法,我宁愿不包含自定义实现。

I'm not using a Javascript framework. 我没有使用Javascript框架。 I'm using Mozilla Rhino, but would prefer to stay away from using the Java library as much as possible, to allow moving my code easily between implementations. 我正在使用Mozilla Rhino,但我希望尽可能远离使用Java库,以便在实现之间轻松移动我的代码。

I want to be able to specify the format of the string, since I want to embed it in a sentence. 我希望能够指定字符串的格式,因为我想将它嵌入句子中。 I want to be able to insert arbitrary on's and at's, and have the full name of the day, not just it's abbreviation. 我希望能够在's和's上插入任意内容,并且拥有当天的全名,而不仅仅是它的缩写。 So toString() won't suffice. 所以toString()是不够的。

有一个名为Datejs的 Javascript免费(和令人敬畏的)库,它为您提供了各种格式化和解析功能(请参阅FormatSpecifiers文档)。

There isn't anything built into JavaScript that allows you to format the display of a date like strftime does. JavaScript中没有任何内容允许您格式化strftime之类的日期显示。

The closest is Date().toLocaleString() , which returns the date as a string formatted according to the local time zone. 最接近的是Date().toLocaleString() ,它将日期作为根据本地时区格式化的字符串返回。

MomentJS有一套非常强大的时间格式选项,最近也有更新。

Dates have a built-in toString: 日期有一个内置的toString:

alert(new Date().toString())

"Sat Dec 19 2009 08:23:33 GMT-0800 (Pacific Standard Time)" “2009年12月19日星期六08:23:33 GMT-0800(太平洋标准时间)”

You could use 你可以用

new Date().toString()

...to get a localized output of the date. ...获取日期的本地化输出。

You could use my JavaScript implementation of Java's SimpleDateFormat : http://www.timdown.co.uk/code/simpledateformat.php . 您可以使用Java的SimpleDateFormat的 JavaScript实现: http//www.timdown.co.uk/code/simpledateformat.php It's a little lighter than date.js and is kept up to date as it is included in log4javascript . 它比date.js轻一点,并且保持最新,因为它包含在log4javascript中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM