It is normal situation that the server, client, database have different timezone.

In this blog post, I will introduce my coding practice to handle multiply timezone in web development.

  • To check current timezone setting. Use date command
Sat Dec 29 21:58:17 JST 2018
  • Or use command ls -al /etc/localtime
lrwxrwxrwx 1 root root 30 Oct 31 06:01 /etc/localtime -> /usr/share/zoneinfo/Asia/Tokyo
  • All available timezones are listed in usr/share/zoneinfo
  • To set timezone permanently. Use commands
rm -rf /etc/localtime
ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime
  • To start node server with specific timezone setting
env TZ="UTC" node app.js
  • To start chrome in specific timezone setting
env TZ='Asia/Bangkok' google-chrome "--user-data-dir=$HOME/chrome-profile"
  • To check running environment timezone offset in Javascript
console.log(new Date().getTimezoneOffset())
# output: -540
# -540 minutes => -9 hours => UTC+9 (Asia/Tokyo)
  • Use following utility functions toServerDate and toClientDate to handle Date object correctly
const serverTimezoneOffset = -540
const clientTimezoneOffset = new Date().getTimezoneOffset()
export const toServerDate = date => new Date(date.getTime() + ms(`${serverTimezoneOffset - clientTimezoneOffset} min`))
export const toClientDate = date => new Date(date.getTime() + ms(`${clientTimezoneOffset - serverTimezoneOffset} min`))

serverTimezoneOffset is your server fixed timezone.

Usage example:

  • To display a time object received from server. Use toClientDate(date).toLocaleString(). For example server passes 27/11/2018 3:00PM in UTC+9, client receives this date object and want to display exactly 27/11/2018 3:00PM in client view. If the client just uses date.toLocaleString(), the printed value will be 27/11/2018 1:00PM
  • To convert date objected created in client (for e.g. 27/11/2018 3:00PM in UTC+7), and want to send to server the date object with the same timing but in server timezone setting (i.e. 27/11/2018 3:00PM in UTC+9). Use toServerDate(date)