时间戳 转换为 年月日 的字符串
/**
* 时间戳转换为日期字符串方法
* @param {*} timesStamp // 时间戳
* @param {*} datePattern // 转换格式
* @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
}
// 调用方法
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 需要区分大小写
- Y(年) 做了大小写兼容, 可以使用 yyyy; D(日) 如果想用小写, 需要修改 "D+" ==改为=> "d+"
日期字符串 转换为 时间戳
const dates = '2021-12-30 15:40:30'
// safari 浏览器需要转换格式为 '2021/12/30 15:40:30'
const timesStamp = new Date(dates).getTime()
console.log(timesStamp) // 输出: 1640850030000
注意: 因为 safari 浏览器的兼容问题, 上面例子中的转换会出错, 需要改为这样的格式 '2021/12/30 15:40:30'
时间戳转化 ( 指定时区 )
场景:例如有一个大型活动,报名时间是 北京时间【2022年4月24 10:00:00 - 14:00:00】,但是用户曾出差英国,电脑设置时区忘记改回中国时区,那么转化后的时间就是 【2022年4月24日 05:00:00 - 09:00:00】
// 解决方法, 在转化之前 对时间戳做计算处理
/** 区分时区的时间转换
* times: 需要转化的时间戳
* type: 年月日格式
* zone: 目标时区 (北京时间 东八区)
*/
export function UTCtimeToString(times, type = '', zone = -8) {
// 格林威治子午线上的地方时 为 0; 以东为负 以西为正
let targetTimezone = zone;
let _dif = new Date().getTimezoneOffset();
let _nowTime = times ? times : new Date().getTime();
// 目标时区时间 = 本地时区时间 + 本地时区时差 - 目标时区时差
let _result = _nowTime + _dif * 60 * 1000 - targetTimezone * 60 * 60 * 1000;
// 调用时间戳转换方法
return datesFormat(_result, type);
}
//调用方法
const str = `中国北京时间: ${UTCtimeToString(1650765600000)} - ${UTCtimeToString(1650780000000, 'hh:mm:ss')}
// 输出内容: 中国北京时间: 2022年4月24 10:00:00 - 14:00:00
或者引用 Moment.js 库; 地址链接: http://momentjs.cn/
GMT标准时间字符串 转换 时间戳
场景: 接口响应头 (response header) 中返回了当前服务器时间, 例如 Date: Mon, 14 Aug 2023 07:04:19 GMT, 然后我们需要获取它, 并将它转化为时间戳后在项目中应用
// 第一步: 获取参数, 以 axios 请求为例
import axios from "axios";
axios.get('/users')
.then(res => {
console.log(res); // res 打印的内容应该如下, 我们重点关注 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
...
} */
});
如果发现 接口响应头中有 Date, 但是前端获取的 headers 中没有 date 数据, 需要请服务端同学在服务器端帮忙配置下 Access-Control-Expose-Headers: [ Date ]
// 第二步: GMT date 字符串转化为时间戳
const _sysTime = new Date((res.headers.date).replace(/,/, '')).getTime()
console.log(_sysTime) // 1691996659200
// 然后我们在逆向转译验证一下
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 (中国标准时间)
如果你仔细对比可能会发现, 接口返回的 Date 与 我们本地 new Date() 输出的 格式与时间 并不一致
猜测是因为: 接口返回的响应头里的 Date 是 格林尼治时间, 与北京时间相差 8 个时区差 (但是返回的 Date 貌似无法修改), 虽然如此, 但是执行 new Date() 后就正常了 (应该是有默认的时区处理机制, 这个没有去深入研究了)
TIP: 注意在转译前, 需要使用正则 replace(/,/, '') 处理下 Date 字符串, 将星期英文缩写后面的逗号去掉, 否则会转译失败