我有一个日期,格式是2014年5月11日太阳。如何使用JavaScript将其转换为2014-05-11 ?
函数taskDate(dateMilli) {
var d = (new Date(dateMilli) + ")。分割(' ');
D [2] = D [2] + ',';
返回[d[0], d[1], d[2], d[3]]。加入(' ');
}
var datemilli =日期。解析(' 2014年5月11日');
console.log (taskDate (datemilli));
上面的代码给了我相同的日期格式,2014年5月11日。我该如何解决这个问题?
2021年的解决方案使用Intl。
现在所有浏览器都支持新的Intl对象。
您可以通过选择使用所需格式的“区域设置”来选择格式。
瑞典语言环境使用的格式是"yyyy-mm-dd":
// Create a date
const date = new Date(2021, 10, 28);
// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');
// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"
使用Intl的缺点:
使用此方法不能“取消格式化”或“解析”字符串
你必须搜索所需的格式(例如在维基百科上),不能使用像“yyyy-mm-dd”这样的格式字符串。
const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
您可以使用padstart。
padStart(n, '0')确保字符串中至少有n个字符,并在它前面加上'0',直到达到该长度。
Join('-')连接一个数组,在每个元素之间添加'-'符号。
getMonth()从0开始,因此是+1。
你可以:
函数formatDate(日期){
var d = new Date(日期),
月= " + (d.getMonth() + 1) ",
day = " + d.getDate(),
year = d.g getfullyear ();
如果(月。长度< 2)
月= '0' +月;
如果一天。长度< 2)
Day = '0' + Day;
返回[年,月,日].join('-');
}
console.log(formatDate('Sun May 11,2014'));
使用的例子:
console.log(formatDate('Sun May 11,2014'));
输出:
2014-05-11
JSFiddle的演示:http://jsfiddle.net/abdulrauf6182012/2Frm3/