各種時間格式轉換、時間戳轉換
阿新 • • 發佈:2021-01-21
1、後端介面返回時間格式轉換成時間戳
例:2021-02-15T09:33:08.694+0000
方案1:
const time =2021-02-15T09:33:08.694+0000
時間戳:new Date(time).getTime()
方案2: 安裝moment
import moment from 'moment';
consttime =2021-02-15T09:33:08.694+0000
時間戳:moment(time).valueOf()
2、後端返回時間格式轉換成 展示的時間狀態 例如2021-02-15T09:33:08.694+0000 =>2021-02-1509:33:08 方案1:安裝moment import moment from 'moment';consttime =2021-02-15T09:33:08.694+0000
時間:moment(time).format('YYYY-MM-DD HH:mm:ss)
方案2:不展示
使用正則表示式分別找到'T'、'.'的索引值,然後字串的方式擷取
3、時間戳展示成展示格式(2020-12-04 15:22:42)或者年月日
可直接引用此函式
getTsFormatDate(timeStamp) { var date = new Date(timeStamp); var year = date.getFullYear(); var month = date.getMonth() + 1; var strDate = date.getDate(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds();if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } if (hours >= 0 && hours <= 9) { hours = "0" + hours; } if (minutes >= 0 && minutes <= 9) { minutes = "0" + minutes; } if (seconds >= 0 && seconds <= 9) { seconds = "0" + seconds; } var currentdate = `${year}-${month}-${strDate} ${hours}:${minutes}:${seconds}`; //或年月日 (注意展示年月日的時候上面的month、strDate、hours、minutes、seconds可不做加0處理) //var currentdate = `${year}年${month}月${strDate}日 ${hours}時${minutes}分${seconds}秒`; return currentdate; }
4、擴充套件
// 將當前時間換成時間格式字串
var timestamp3 = 1403058804;
var newDate = new Date();
newDate.setTime(timestamp3 * 1000);
// Wed Jun 18 2014
console.log(newDate.toDateString());
// Wed, 18 Jun 2014 02:33:24 GMT
console.log(newDate.toGMTString());
// 2014-06-18T02:33:24.000Z
console.log(newDate.toISOString());
// 2014-06-18T02:33:24.000Z
console.log(newDate.toJSON());
// 2014年6月18日
console.log(newDate.toLocaleDateString());
// 2014年6月18日 上午10:33:24
console.log(newDate.toLocaleString());
// 上午10:33:24
console.log(newDate.toLocaleTimeString());
// Wed Jun 18 2014 10:33:24 GMT+0800 (中國標準時間)
console.log(newDate.toString());
// 10:33:24 GMT+0800 (中國標準時間)
console.log(newDate.toTimeString());
// Wed, 18 Jun 2014 02:33:24 GMT
console.log(newDate.toUTCString());