简体   繁体   中英

Convert a date to string in Javascript

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 strftime in Ruby, C, and many other languages.

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.

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.

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

There isn't anything built into JavaScript that allows you to format the display of a date like strftime does.

The closest is Date().toLocaleString() , which returns the date as a string formatted according to the local time zone.

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

Dates have a built-in toString:

alert(new Date().toString())

"Sat Dec 19 2009 08:23:33 GMT-0800 (Pacific Standard Time)"

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 . It's a little lighter than date.js and is kept up to date as it is included in log4javascript .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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