假设有一个日期:
var date_not_formatted=new Date(timestamp);
var dateFormatted=new Date(date_not_formatted.getFullYear()+"-"+(date_not_formatted.getMonth()+1)+"-"+date_not_formatted.getDate());
我将此数据放入输入类型日期中,并在控制台中读取以下警告:
The specified value "Sat Sep 15 2018 00:00:00 GMT+0200 (daylight savings time
dell\u2019central Europe)" does not conform to the required format, "yyyy-MM-dd".
有人可以帮助我吗?
最佳答案
如果要将日期转换为yyyy-MM-dd,可以执行以下操作:
var timestamp = 1537345115000;
var date_not_formatted = new Date(timestamp);
var formatted_string = date_not_formatted.getFullYear() + "-";
if (date_not_formatted.getMonth() < 9) {
formatted_string += "0";
}
formatted_string += (date_not_formatted.getMonth() + 1);
formatted_string += "-";
if(date_not_formatted.getDate() < 10) {
formatted_string += "0";
}
formatted_string += date_not_formatted.getDate();
console.log(formatted_string);
注意:
getMonth()
将返回从零开始的值。