我注意到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")
在调用new Date()
函数时,我找不到任何显示所有有效字符串格式的文档。
这是用于将字符串转换为日期。如果我们从相反的角度看,也就是将日期对象转换为字符串,直到现在,我仍然觉得JavaScript没有内置的API将日期对象格式化为字符串。
编者注: 以下方法是提问者的企图是工作在一个特定的浏览器,但确实 不是 一般的工作; 请参阅本页上的答案 以查看一些实际解决方案。
今天,我在toString()
date对象上使用了该方法,令人惊讶的是,它用于将date格式化为字符串的目的。
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
同样在这里,我找不到关于将日期对象格式化为字符串的所有方式的任何文档。
列出Date()
对象支持的格式说明符的文档在哪里?
基本上,你有三种方法,必须自己组合字符串:
getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
例:
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);