如何以YYYY-MM-DD格式获取日期? [英] How do I get a date in YYYY-MM-DD format?
问题描述
通常情况下,如果我想得到日期,我可以做类似的事情
Normally if I wanted to get the date I could just do something like
var d = new Date();
console.log(d);
这样做的问题是,当我运行该代码时,它返回:
The problem with doing that, is when I run that code, it returns:
2015年8月24日星期一4:20:00 GMT-0800(太平洋标准时间)
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
如何让Date()方法返回MM-DD-YYYY格式的值,以便返回如下内容:
How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:
2015年8月24日
8/24/2015
或者,也许是MM-DD-YYYY H :M
Or, maybe MM-DD-YYYY H:M
2016年8月24日4:20
8/24/2016 4:20
推荐答案
以下代码是一种方法。如果您有日期,请将其传递给 convertDate()
函数,它将返回YYYY-MM-DD格式的字符串:
The below code is a way of doing it. If you have a date, pass it to the convertDate()
function and it will return a string in the YYYY-MM-DD format:
var todaysDate = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
console.log(convertDate(todaysDate)); // Returns: 2015-08-25
这篇关于如何以YYYY-MM-DD格式获取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!