Javascript 在Javascript中将日期转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1933320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a date to string in Javascript
提问by wvdschel
I'm looking for a way to convert a Javascript Date object to a string. I'm converting my site from Ruby to server side Javascript, and I'm looking for something analogous to strftimein Ruby, C, and many other languages.
我正在寻找一种将 Javascript 日期对象转换为字符串的方法。我正在将我的网站从 Ruby 转换为服务器端 Javascript,并且我正在寻找类似于strftimeRuby、C 和许多其他语言的内容。
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. 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.
我没有使用 Javascript 框架。我正在使用 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. So toString() won't suffice.
我希望能够指定字符串的格式,因为我想将它嵌入一个句子中。我希望能够插入任意的 on 和 at,并获得当天的全名,而不仅仅是缩写。所以 toString() 是不够的。
采纳答案by gusterlover6
回答by Josh Stodola
There is a free (and awesome) library for Javascript called Datejsthat gives you all sorts of formatting and parsing capabilities (see the FormatSpecifiersdocumentation).
有一个免费(而且很棒)的 Javascript 库,称为Datejs,可为您提供各种格式化和解析功能(请参阅FormatSpecifiers文档)。
回答by Paul D. Waite
There isn't anything built into JavaScript that allows you to format the display of a date like strftimedoes.
JavaScript 中没有任何内置功能可以让您像strftime这样设置日期的显示格式。
The closest is Date().toLocaleString(), which returns the date as a string formatted according to the local time zone.
最接近的是Date().toLocaleString(),它将日期作为根据本地时区格式化的字符串返回。
回答by Annie
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(太平洋标准时间)”
回答by tangens
You could use
你可以用
new Date().toString()
...to get a localized output of the date.
...获取日期的本地化输出。
回答by Tim Down
You could use my JavaScript implementation of Java's SimpleDateFormat: 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.
您可以使用我的 Java 的SimpleDateFormat 的JavaScript 实现:http: //www.timdown.co.uk/code/simpledateformat.php。它比 date.js 轻一点,并且保持最新,因为它包含在log4javascript 中。

