Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

javascript - 在哪里可以找到有关在JavaScript中格式化日期的文档? [关闭](Where can I find documentation on formatting a date in JavaScript? [closed])

I noticed that JavaScript's new Date() function is very smart in accepting dates in several formats.

(我注意到JavaScript的new Date()函数非常聪明,可以接受多种格式的日期。)

Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")

I could not find documentation anywhere showing all the valid string formats while calling new Date() function.

(在调用new Date()函数时,找不到任何显示所有有效字符串格式的文档。)

This is for converting a string to a date.

(这是用于将字符串转换为日期。)

If we look at the opposite side, that is, converting a date object to a string, until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string.

(如果我们从相反的角度来看,也就是将日期对象转换为字符串,直到现在,我仍然觉得JavaScript没有内置的API将日期对象格式化为字符串。)

Editor's note: The following approach is the asker's attempt that worked on a particular browser but does not work in general;

(编者按:以下方法是提问者的企图是工作在一个特定的浏览器,但一般工作;)

see the answers on this page to see some actual solutions.

(请参阅本页上的答案以查看一些实际解决方案。)

Today, I played with the toString() method on the date object and surprisingly it serves the purpose of formatting date to strings.

(今天,我在date对象上使用toString()方法,令人惊讶的是,它用于将日期格式化为字符串的目的。)

var d1 = new Date();
d1.toString('yyyy-MM-dd');       //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome
d1.toString('dddd, MMMM ,yyyy')  //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome

Also here I couldn't find any documentation on all the ways we can format the date object into a string.

(同样在这里,我找不到关于将日期对象格式化为字符串的所有方式的任何文档。)

Where is the documentation which lists the format specifiers supported by the Date() object?

(列出Date()对象支持的格式说明符的文档在哪里?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I love 10 ways to format time and date using JavaScript and Working with Dates .

(我喜欢使用JavaScript“使用日期” 格式化时间和日期的10种方法 。)

Basically, you have three methods and you have to combine the strings for yourself:

(基本上,您有三种方法,必须自己组合字符串:)

getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year

Example:

(例:)

 var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth() + 1; //Months are zero based var curr_year = d.getFullYear(); console.log(curr_date + "-" + curr_month + "-" + curr_year); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...