DEV Community

Masui Masanori
Masui Masanori

Posted on

[TypeScript][Moment] Change timezone

Intro

Sometimes I join online events.
But I don't know when those events will start because the timezone is different from Japan (I live in Japan).

So this time I will try converting.

Environments

  • Node.js ver.16.4.2
  • TypeScript ver.4.3.5
  • moment ver.2.29.1
  • moment-timezone ver.0.5.33
  • ts-loader ver.9.2.3
  • webpack ver.5.42.0
  • webpack-cli ver.4.7.2

Get my own timezone

For getting my own timezone, I just create a Date instance.

const currentDate = new Date();
console.log(currentDate);
Enter fullscreen mode Exit fullscreen mode

Result

Sun Jul 11 2021 08:39:08 GMT+0900 (Japan Standard Time)
Enter fullscreen mode Exit fullscreen mode

The timezone came from OS settings.
So if I change them, the result will be changed.

Convert timezone to my own one?

I can create Data instances by formatted string.

const currentDate = new Date('Jul 10 2021 19:48 EDT');
console.log(currentDate);
Enter fullscreen mode Exit fullscreen mode

Result

Sun Jul 11 2021 08:48:00 GMT+0900 (Japan Standard Time)
Enter fullscreen mode Exit fullscreen mode

I was able to implement everything I wanted to achieve...?

Daylight Saving Time(Summer time)

Because there are "Daylight Saving Time" in some countries, I must change their timezone according the date.
For example, if the date is "2021-03-13", I must use "EST". But if the date is "2021-03-15", I must use "EDT".

The problem is the dates when "Daylight Saving Time" start aren't same in every year.

After all, I used "moment" and "moment-timezone".

Because I can't specify the time zone like "EDT" and "America / EDT", I select cities that belong to that timezone and map the names.

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Convert sample</title>
        <meta charset="utf-8">
    </head>
    <body>
        <input type="date" id="convert_date_from" placeholder="Date From">
        <select id="convert_hour_from"></select>
        <select id="convert_minute_from"></select>
        <input type="text" id="convert_timezone_from" list="convert_timezone_from_list">
            <datalist id="convert_timezone_from_list">

            </datalist>
        <button onclick="Page.convert()">Convert</button>
        <div id="convert_date_to"></div>
        <script src="js/main.page.js"></script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

main.page.ts

import moment from "moment";
import tz from 'moment-timezone';

type TimezoneValue = {
    displayName: string,
    value: string
};
const timezoneValueList: TimezoneValue[] = [
    { displayName: 'US/ET', value: 'America/New_York'},
    { displayName: 'US/CT', value: 'America/Chicago' },
    { displayName: 'US/PT', value: 'America/Los_Angeles' },
    { displayName: 'Japan', value: 'Asia/Tokyo' },
];
function init() {
    addHour();
    addMinute();
    addTimezone();
}
function addHour() {
    const hourInput = document.getElementById('convert_hour_from') as HTMLSelectElement;
    for(let i = 0; i < 24; i++) {
        const hourValue = document.createElement('option');
        const value = ("00"+ i).slice (-2);
        hourValue.text = value;
        hourValue.value = value;
        hourInput.appendChild(hourValue);
    }
}
function addMinute() {
    const minuteInput = document.getElementById('convert_minute_from') as HTMLSelectElement;
    for(let i = 0; i < 60; i++) {
        const minuteValue = document.createElement('option');
        const value = ("00"+ i).slice (-2);
        minuteValue.text = value;
        minuteValue.value = value;
        minuteInput.appendChild(minuteValue);
    }
}
function addTimezone() {
    const timezoneList = document.getElementById('convert_timezone_from_list') as HTMLDataListElement;
    for(const value of timezoneValueList) {
        const timezoneValue = document.createElement('option');
        timezoneValue.value = value.displayName;
        timezoneList.appendChild(timezoneValue);
    }
}
export function convert() {
    const dateInput = document.getElementById('convert_date_from') as HTMLInputElement;
    const hourInput = document.getElementById('convert_hour_from') as HTMLSelectElement;
    const minuteInput = document.getElementById('convert_minute_from') as HTMLSelectElement;
    const timezoneInput = document.getElementById('convert_timezone_from') as HTMLInputElement;

    const date = moment(dateInput.value).format('YYYY-MM-DD');
    const hour = hourInput.options[hourInput.selectedIndex].value;
    const minute = minuteInput.options[minuteInput.selectedIndex].value;
    const datetimeText = `${date} ${hour}:${minute}`;

    const timezone = timezoneValueList.find(t => t.displayName === timezoneInput.value);
    const targetTime =  momentTz.tz(datetimeText, timezone!.value);

    const dateOutput = document.getElementById('convert_date_to') as HTMLElement;
    dateOutput.textContent = moment(targetTime.toDate()).format('YYYY-MM-DD HH:mm');
}
init();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)