在哪里可以找到有关JavaScript格式化日期的文档? [英] Where can I find documentation on formatting a date in JavaScript?
问题描述
我注意到JavaScript的新的Date()
函数在几种格式中接受日期是非常明智的。
I noticed that JavaScript's new Date()
function is very smart in accepting dates in several formats.
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()
函数时,找到任何显示所有有效字符串格式的文档。
I could not find documentation anywhere showing all the valid string formats while calling new Date()
function.
这是为了转换字符串到日期。如果我们看看对面,那就是将日期对象转换成字符串,直到现在我都觉得JavaScript没有一个内置的API来将日期对象格式化成一个字符串。
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.
编者注:以下方法是asker尝试在特定浏览器上工作,但不一般工作查看此页面上的答案以查看一些实际的解决方案。
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.
今天,我玩了code> toString()方法,令人惊讶的是,它的目的是将日期格式化为字符串。
Today, I played with the toString()
method on the date object and surprisingly it serves the purpose of formatting date to strings.
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.
文档中列出了 Date()
支持的格式说明符。对象?
Where is the documentation which lists the format specifiers supported by the Date()
object?
推荐答案
我喜欢 使用JavaScript格式化时间和日期的10种方法 和 使用日期 。
I love 10 ways to format time and date using JavaScript and Working with Dates.
基本上,你有三种方法,你必须结合自己的字符串:
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
示例:
<script type="text/javascript">
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);
</script>
这篇关于在哪里可以找到有关JavaScript格式化日期的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!