javascript - 在哪里可以找到有关在 JavaScript 中格式化日期的文档?

标签 javascript date datetime-format date-format time-format

我注意到 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 来将日期对象格式化为字符串。

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.

今天,我在日期对象上使用了 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

我也在这里找不到任何关于我们可以将日期对象格式化为字符串的所有方式的文档。

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

最佳答案

我爱 10 ways to format time and date using JavaScript Working with Dates .

基本上,你有三个方法,你必须自己组合字符串:

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);

关于javascript - 在哪里可以找到有关在 JavaScript 中格式化日期的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1056728/

相关文章:

Python - 获取日期格式

javascript - 隐藏/显示分区

javascript - 从 JsonResult 返回字符串数组并在 JavaScript 中使用它

c# - 日期月份显示不正确

python - 使用正则表达式提取不同格式的日期并对它们进行排序 - pandas

c# - 发生 DateTimeInvalidLocalFormat

javascript - 如何在 AngularJS 中获取变量的监听器?

javascript - AngularJS:模型值更改时更新选择 View

date - 如何在 RediSearch 中存储日期/时间

python - pd.to_datetime() 解析正确的日期格式时出现奇怪的错误