LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptで日付をフォーマットする

Posted at

1. やること

  • JavaScript(TypeScript)でDateをフォーマットした文字列を取得する

2. バージョンなど

  • "typescript": "^4.4.4",

3. やったこと

3.1. Intl.DateTimeFormatを使った

  • Intl.DateTimeFormat
  • サンプルコードは以下
    • Intl.DateTimeFormat().resolvedOptions().localeでロケールを取得できる
    • Intl.DateTimeFormat().resolvedOptions().timeZoneでタイムゾーンを取得できる
    • formatToPartsでパーツごとのフォーマット値が取得できるので、それを利用してフォーマットできる
format(date: Date): string {
    const locale = Intl.DateTimeFormat().resolvedOptions().locale;
    const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    const formatter = new Intl.DateTimeFormat(
        locale,
        {
            timeZone: timeZone,
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        }
    );

    const parts = formatter.formatToParts(date.getTime())
        .reduce((map, entry) => {
            map[entry.type] = entry.value;
            return map;
        }, {} as {[k: string]: string});

        return `${parts.year}/${parts.month}/${parts.day} ${parts.hour}:${parts.minute}:${parts.second}`;
}

3.2. テストコード

3.2.1. デフォルトのタイムゾーンの場合
  • ここでは、デフォルトのタイムゾーンはAsia/Tokyoとする
  • サンプルコードは以下
test("get correct formatted value", () => {
    const date = new Date(Date.UTC(2022, 0, 30, 0, 10, 20));

    const actual = DateTimeDemo.format(date);

    expect(actual).toEqual("2022/01/30 09:10:20");
})

3.2.2. テスト実行時のタイムゾーンを固定する場合
  • jest.config.jsprocess.env.TZを設定して固定する
  • jest.config.jsの記述例は以下
process.env.TZ = 'Asia/Tokyo';

module.exports = {
  moduleFileExtensions: ['js', 'ts', 'tsx'],
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
  },
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.json',
    },
  },
}
3.2.3. 他のタイムゾーンを検証したい場合
  • Intl.DateTimeFormat().resolvedOptions().timeZoneをモックする
  • モックの記載例は以下
describe("another timezone(America/New_York)", () => {
    // UTC offset = −05:00

    beforeAll(() => {
        const DateTimeFormat = Intl.DateTimeFormat;
        jest.spyOn(Intl, 'DateTimeFormat')
            .mockImplementation((locale, options) => {
                return new DateTimeFormat(
                    locale,
                    {
                        ...options,
                        timeZone: "America/New_York"
                    }
                )
            })
    })
    afterAll(() => {
        jest.restoreAllMocks();
    })

    test("get correct formatted value", () => {
        const date = new Date(Date.UTC(2022, 0, 30, 0, 10, 20));

        const actual = DateTimeDemo.format(date);

        expect(actual).toEqual("2022/01/29 19:10:20");
    })
})

おわり。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0