時間戳 轉(zhuǎn)換為 年月日 的字符串
/**
* 時間戳轉(zhuǎn)換為日期字符串方法
* @param {*} timesStamp // 時間戳
* @param {*} datePattern // 轉(zhuǎn)換格式
* @returns
*/
function datesFormat(timesStamp, datePattern = '') {
return (new Date(parseInt(timesStamp)).format(datePattern ? datePattern : 'YYYY-MM-DD hh:mm:ss'))
}
Date.prototype.format = function(fmt) {
var o = {
"M+" : this.getMonth()+1, //月份
"D+" : this.getDate(), //日
"h+" : this.getHours(), //小時
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
}
if(/(Y+)/i.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt
}
// 調(diào)用方法
const timesStamp = '1640850030000'
const dates = datesFormat(timesStamp, 'YYYY年MM月DD日 hh:mm:ss')
console.log(dates) // 輸出: 2021年12月30日 15:40:30
說明:
- 因為 M(月) 與 m(分鐘) 表示不同意思, 所以 M & m 需要區(qū)分大小寫
- Y(年) 做了大小寫兼容, 可以使用 yyyy; D(日) 如果想用小寫, 需要修改 "D+" ==改為=> "d+"
日期字符串 轉(zhuǎn)換為 時間戳
const dates = '2021-12-30 15:40:30'
// safari 瀏覽器需要轉(zhuǎn)換格式為 '2021/12/30 15:40:30'
const timesStamp = new Date(dates).getTime()
console.log(timesStamp) // 輸出: 1640850030000
注意: 因為 safari 瀏覽器的兼容問題, 上面例子中的轉(zhuǎn)換會出錯, 需要改為這樣的格式 '2021/12/30 15:40:30'
時間戳轉(zhuǎn)化 ( 指定時區(qū) )
場景:例如有一個大型活動,報名時間是 北京時間【2022年4月24 10:00:00 - 14:00:00】,但是用戶曾出差英國,電腦設置時區(qū)忘記改回中國時區(qū),那么轉(zhuǎn)化后的時間就是 【2022年4月24日 05:00:00 - 09:00:00】
// 解決方法, 在轉(zhuǎn)化之前 對時間戳做計算處理
/** 區(qū)分時區(qū)的時間轉(zhuǎn)換
* times: 需要轉(zhuǎn)化的時間戳
* type: 年月日格式
* zone: 目標時區(qū) (北京時間 東八區(qū))
*/
export function UTCtimeToString(times, type = '', zone = -8) {
// 格林威治子午線上的地方時 為 0; 以東為負 以西為正
let targetTimezone = zone;
let _dif = new Date().getTimezoneOffset();
let _nowTime = times ? times : new Date().getTime();
// 目標時區(qū)時間 = 本地時區(qū)時間 + 本地時區(qū)時差 - 目標時區(qū)時差
let _result = _nowTime + _dif * 60 * 1000 - targetTimezone * 60 * 60 * 1000;
// 調(diào)用時間戳轉(zhuǎn)換方法
return datesFormat(_result, type);
}
//調(diào)用方法
const str = `中國北京時間: ${UTCtimeToString(1650765600000)} - ${UTCtimeToString(1650780000000, 'hh:mm:ss')}
// 輸出內(nèi)容: 中國北京時間: 2022年4月24 10:00:00 - 14:00:00
或者引用 Moment.js 庫; 地址鏈接: http://momentjs.cn/
GMT標準時間字符串 轉(zhuǎn)換 時間戳
場景: 接口響應頭 (response header) 中返回了當前服務器時間, 例如 Date: Mon, 14 Aug 2023 07:04:19 GMT, 然后我們需要獲取它, 并將它轉(zhuǎn)化為時間戳后在項目中應用
// 第一步: 獲取參數(shù), 以 axios 請求為例
import axios from "axios";
axios.get('/users')
.then(res => {
console.log(res); // res 打印的內(nèi)容應該如下, 我們重點關注 headers
/** {
config: { url: '/users', method:'get', data:{}, ... }
data: { code: 200, msg:'success', data: [] }
headers: {
content-type: "application/json"
date: "Mon, 14 Aug 2023 07:04:19 GMT"
}
request: XMLHttpRequest { ... }
status: 200
...
} */
});
如果發(fā)現(xiàn) 接口響應頭中有 Date, 但是前端獲取的 headers 中沒有 date 數(shù)據(jù), 需要請服務端同學在服務器端幫忙配置下 Access-Control-Expose-Headers: [ Date ]
// 第二步: GMT date 字符串轉(zhuǎn)化為時間戳
const _sysTime = new Date((res.headers.date).replace(/,/, '')).getTime()
console.log(_sysTime) // 1691996659200
// 然后我們在逆向轉(zhuǎn)譯驗證一下
const _gmtTime = new Date(_sysTime)
console.log(_gmtTime) // Mon Aug 14 2023 15:04:19 GMT+0800 (中國標準時間)
console.log( new Date() ) // Mon Aug 14 2023 15:04:19 GMT+0800 (中國標準時間)
如果你仔細對比可能會發(fā)現(xiàn), 接口返回的 Date 與 我們本地 new Date() 輸出的 格式與時間 并不一致
猜測是因為: 接口返回的響應頭里的 Date 是 格林尼治時間, 與北京時間相差 8 個時區(qū)差 (但是返回的 Date 貌似無法修改), 雖然如此, 但是執(zhí)行 new Date() 后就正常了 (應該是有默認的時區(qū)處理機制, 這個沒有去深入研究了)
TIP: 注意在轉(zhuǎn)譯前, 需要使用正則 replace(/,/, '') 處理下 Date 字符串, 將星期英文縮寫后面的逗號去掉, 否則會轉(zhuǎn)譯失敗