时间格式转换,转时间戳,转UTC,转中国标准时间

问题:在实际开发中后端要求需要UTC格式 2022-11-30T16:00:00.000Z

           而我拿到的格式是中国标准时间或2022-12

解决思路:把拿到的时间转为时间戳,在进行转格式

一、时间转换为时间戳

// 北京时间:2021-11-18 22:14:24
/* 时间yyyy-MM-dd HH:mm:ss转为时间戳 */
timeToTimestamp(time) {
    let timestamp = Date.parse(new Date(time).toString());
    //timestamp = timestamp / 1000; //时间戳为13位需除1000,时间戳为13位的话不需除1000
    // console.log(time + "的时间戳为:" + timestamp);
    return timestamp;
    //2021-11-18 22:14:24的时间戳为:1637244864707
},

Date.parse()分析一个包含日期的字符串,函数的返回值为Number类型,返回该字符串所表示的日期与 1970 年 1 月 1 日午夜之间相差的毫秒数。

二、时间戳转化为时间

// 时间戳:1637244864707
/* 时间戳转换为时间 */
timestampToTime(timestamp) {
  timestamp = timestamp ? timestamp : null;
  let date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
}

三、时间字符串转换为时间

let str = '2021年12月10日 09:27';
let replacedStr = str.replace('年', '-').replace('月', '-').replace('日', '');
console.log(replacedStr); //2021-12-10 09:27
let parsedDate = new Date(replacedStr);
console.log(parsedDate); //Fri Dec 10 2021 09:27:00 GMT+0800 (中国标准时间)

四、中国标准时间转化为UTC时间

用上面的方法先转换为时间戳,再用toISOString() 方法转换为UTC格式

 this.readData.month = this.timeToTimestamp(this.readData.month)
 // console.log("转为时间戳之后的month",this.readData.month)
 let d = new Date(this.readData.month);
 // console.log("dddd1111",d)
 d = d.toISOString()
 // console.log("转为UTC格式",d)

同理:转换为中国标椎时间

          先转时间戳,再用toUTCString() 方法转换

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值