本文翻译自:Format JavaScript date as yyyy-mm-dd
I have a date with the format Sun May 11,2014
. 我有一个日期为Sun May 11,2014
。 How can I convert it to 2014-05-11
using JavaScript? 如何使用JavaScript将其转换为2014-05-11
?
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
taskdate(datemilli);
The code above gives me the same date format, sun may 11,2014
. 上面的代码为我提供了相同的日期格式,即sun may 11,2014
。 How can I fix this? 我怎样才能解决这个问题?
#1楼
参考:https://stackoom.com/question/1azd6/将JavaScript日期格式设置为yyyy-mm-dd
#2楼
You can do: 你可以做:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
Usage example: 用法示例:
alert(formatDate('Sun May 11,2014'));
Output: 输出:
2014-05-11
Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/ JSFiddle上的演示: http : //jsfiddle.net/abdulrauf6182012/2Frm3/
#3楼
Here is one way to do it: 这是一种实现方法:
var date = Date.parse('Sun May 11,2014');
function format(date) {
date = new Date(date);
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return year + '-' + month + '-' + day;
}
console.log(format(date));
#4楼
format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
Result: 结果:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
#5楼
If the date needs to be the same across all time zones, for example represents some value from the database, then be sure to use UTC versions of the day, month, fullyear functions on the JavaScript date object as this will display in UTC time and avoid off-by-one errors in certain time zones. 如果日期在所有时区都需要相同,例如代表数据库中的某个值,那么请确保在JavaScript日期对象上使用UTC版本的日,月,全年功能,因为它将以UTC时间和避免在某些时区出现一对一的错误。
Even better, use the Moment.js date library for this sort of formatting. 更好的是,使用Moment.js日期库进行这种格式化。
#6楼
I suggest using something like formatDate-js instead of trying to replicate it every time. 我建议使用诸如formatDate-js之类的方法,而不是每次尝试复制它。 Just use a library that supports all the major strftime actions. 只需使用支持所有主要strftime动作的库即可。
new Date().format("%Y-%m-%d")