简体   繁体   English

如何模拟dayjs时区

[英]How to mock dayjs timezone

I have a function that translates a date in format 2021-06-07T07:28:55.69725+00:00 into string of hours and minutes in format 07:28我有一个 function 将格式2021-06-07T07:28:55.69725+00:00的日期转换为格式为07:28的小时和分钟字符串

export function getTime(dateTime: string) {
  return dayjs(dateTime).format("HH:mm");
}

Currently I'm locating in UTC+5, so the answer of this function to the argument 2021-06-07T07:28:55.69725+00:00 is 12:28 .目前我位于 UTC+5,所以这个 function 对参数2021-06-07T07:28:55.69725+00:00的答案是12:28 I want to test the work of the function but I need to mock timezone so that tests would be ok on machines in different timezones.我想测试 function 的工作,但我需要模拟时区,以便在不同时区的机器上进行测试。 I tried next code but it still returns 12:28 .我尝试了下一个代码,但它仍然返回12:28

import dayjs from "dayjs";
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(timezone)

describe('Function getTime', () => {
  beforeEach(() => {
    dayjs.tz.setDefault('Europe/Moscow');
  })

  afterEach(() => {
    dayjs.tz.setDefault();
  })

  it('should return time in format hh:mm', () => {
    const dateTime = '2021-06-07T07:28:55.69725+00:00';
    expect(getTime(dateTime)).toEqual('10:28');
  })
})

The problem is, that dayjs.tz.setDefault('Europe/Moscow') affects only dayjs.tz().问题是,dayjs.tz.setDefault('Europe/Moscow') 只影响 dayjs.tz()。 It means, that dayjs() will still show your local time.这意味着 dayjs() 仍将显示您的当地时间。

You should change your function:你应该改变你的 function:

export function getTime(dateTime: string) {   
    return dayjs.tz(dateTime).format("HH:mm"); 
}

Now it should work as you expect.现在它应该可以按您的预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM