shou2017.com
JP

Get Japan time and calculate dates in JavaScript

Tue Sep 13, 2022
Sat Aug 10, 2024

I fiddled with Lambda’s timezone settings, so here’s a note.

Lambda’s timezone is one of those tricky things. You can fix it by setting the TZ environment variable, but that’s not recommended.

Don’t set Lambda’s timezone with the TZ environment variable

So, you need to handle Japan time in JavaScript. You can use a library, but it’s also easy to do without one.

Get Japan time

The default timezone is UTC, so ideally you want to get Japan time without relying on the runtime environment.

This blog was helpful:

Always get JST (Japan time) in JavaScript regardless of runtime environment

JavaScript’s new Date() is affected by the runtime’s timezone. If you can specify Asia/Tokyo in Date#toLocaleString(), that’s great, but some machines don’t have the Japan timezone defined.

// This will always get Japan time
const jstNow = new Date(Date.now() + ((new Date().getTimezoneOffset() + (9 * 60)) * 60 * 1000));
console.log(jstNow);

This works even in Lambda, which doesn’t have the Japan timezone defined.

At first, I thought this was fine, but the return value is like 2022-09-13T11:50:14.999Z, so you have to format it every time. If you don’t need to do date calculations, it’s not a big deal, but sometimes it’s a hassle.

So, I used Intl.DateTimeFormat.

With Intl.DateTimeFormat, you can format dates according to language.

If you set timeZone to Asia/Tokyo, it will convert to Japan time.

const dateTimeFormat = new Intl.DateTimeFormat("ja-JP", {
  month: "long",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  hourCycle: "h23",
  timeZone: "Asia/Tokyo"
});
console.log(dateTimeFormat.format(new Date()));
> 9月13日 21:06

Date calculations

For adding or subtracting dates, you can use functions like these. For subtraction, just change + to -.

Date.prototype.addDays = function (days) {
  const date = new Date(this.valueOf());
  date.setDate(date.getDate() + days);
  return date;
};
Date.prototype.addHours = function (hours) {
  this.setTime(this.getTime() + hours * 60 * 60 * 1000);
  return this;
};
console.log(dateTimeFormat.format(date.addDays(7)));
console.log(dateTimeFormat.format(date.addHours(1)));

>9月20日 21:22
>9月13日 22:22

That’s all. I initially used a library for this, but it turns out you can do it pretty easily without one.

See Also