JS里的Date对象并未提供时间格式化方法:
var date = new Date();
console.log(date.getFullYear());//年份
console.log(date.getMonth()+1);//月份,注意getMonth()返回值为0-11,故必需加上1;
console.log(date.getDate());//一个月的第几天
console.log(date.getHours());//时
console.log(date.getMinutes());//分
console.log(date.getSeconds());//秒
要想返回格式化的时间可以封装一个方法实现:
JS的数字转字符串是:
var n = 1234;
console.log(n.toString());
比如想得到 yyyyMMdd的格式化时间字符串:
var getYYYYMMDD(){
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
var currentDay = '';
if(month>9){
currentDay += year.toString() + month.toString() + day.toString();
}
else{
currentDay += year.toString() + '0' + month.toString() + day.toString();
}
return currentDay;
}
补充:
字符串转数字的方法:
https://blog.youkuaiyun.com/Inuyasha1121/article/details/40182105