前端日期格式转换
1.获取当前年月日时分秒
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); // JavaScript的月份是从0开始的,所以需要加1
const day = date.getDate();
const hours = date.getHours().toString().padStart(2, '0'); // 补零
const minutes = date.getMinutes().toString().padStart(2, '0'); // 补零
const sec = date.getSeconds().toString().padStart(2, '0'); // 补零
let currentDate = `${year}-${month}-${day} ${hours}:${minutes}:${sec}`;
console.log(currentDate) //2024-11-12 11:10:16
2.将时间格式带T的时间转化
let date0 = "2024-11-12T11:10:16.000+00:00"
let date1 = new Date(date0); //转化为国际时间
let date2 = date1.toJSON().substr(0, 19).replace("T", " ")
console.log(date2) //2024-11-12 11:10:16
不建议使用new Date()的对象方法,不然因为时区原因,会有8小时的时差
3.时间格式转化封装方法
function formatTime(time, format) {
const date = new Date(time);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); // JavaScript的月份是从0开始的,所以需要加1
const day = date.getDate();
const hours = date.getHours().toString().padStart(2, '0'); // 补零
const minutes = date.getMinutes().toString().padStart(2, '0'); // 补零
const sec = date.getSeconds().toString().padStart(2, '0'); // 补零
let currentDate = `${year}-${month}-${day} ${hours}:${minutes}:${sec}`;
console.log(currentDate) //2024-11-12 11:10:16
let result = '';
switch (format) {
case 'yyyy-MM-dd':
result = `${year}-${month}-${day}`;
break;
case 'yyyy/MM/dd':
result = `${year}/${month}/${day}`;
break;
case 'yyyy年MM月dd日':
result = `${year}年${month}月${day}日`;
break;
case 'HH:mm:ss':
result = `${hours}:${minutes}:${sec}`;
break;
default:
result = `${year}-${month}-${day} ${hours}:${minutes}:${sec}`;
}
return result;
}
4.如果不想自己写方法,可以引入moment.js库,
Moment.js 是一个 JavaScript 日期处理类库,用于解析、检验、操作、以及显示日期。
官网:https://momentjs.cn/