使用Moment Timezone将时间转换为目标时区的时间

1.moment-timezone

 moment是一个强大JavaScript 日期处理类库,但为了根据时区计算对应的时间时,一般会采用手动设置时间偏移量的方法,使用起来十分繁琐。于是就有了moment-timezone,JavaScript 时区处理类库。moment-timezone可以视为在moment的基础上多封装了一个时区转换方法的js库,所以moment的使用方法在moment-timezone中也基本都可以实现。

2.moment-timezone安装
npm install moment-timezone --save    # npm
yarn add moment-timezone              # Yarn
yarn add @types/moment-timezone       # TypeScript

官方地址: http://momentjs.cn/timezone/
github地址: https://github.com/moment/moment-timezone

3.moment-timezone使用
import moment_tz from 'moment-timezone';

const dateWithZone1 = moment_tz(new Date('2021-03-30T11:03:20Z')).tz( 'Asia/Shanghai');
const dateWithZone2 = moment_tz(new Date('2021-03-30T11:03:20Z')).tz( 'Asia/Tokyo');
const ShanghaiTimezoneDate= dateWithZone1.format('YYYY-MM-DD kk:mm:ss');
// 此处kk代表24小时制度的时间,hh是12小时制
const TokyoTimezoneDate= dateWithZone2.format('YYYY-MM-DD kk:mm:ss');

// ShanghaiTimezoneDate:2021-03-30 19:03:20
// TokyoTimezoneDate:2021-03-30 20:03:20

下面两种写法的作用相同

const timeA = moment_tz.tz("2013-11-18 11:55", "Asia/Shanghai");
const timeB = moment_tz("2013-11-18 11:55").tz("Asia/Shanghai");
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值