Site icon Coding is Love

Get Date of a specific time zone in Javascript

timezone date in javascript

I was recently working on an API which should return data for yesterday. I used normal date object in JS and extracted the date from that object. It worked fine locally and I deployed it to server.

It was returning the wrong date on the production server. This is when I realized that the server is in the US region and it is returning date as per the US timezone.

Now I had to get date based on timezone in JS. I tried searching online but most of the solutions were kind of vague and not really the ideal solutions.

Finally I had to use js-joda which is a really good date and time library in javascript. It was pretty easy to get date based on timezone using this library. Here’s how to do it!

var zdt = ZonedDateTime.now(ZoneId.of("UTC+05:30"));

All you need to do is specify the timezone in UTC offset or the time zone name. Here’s an example with timezone name

var zdt = ZonedDateTime.now(ZoneId.of("Europe/Paris"))

You can read the documentation of js-joda here – https://js-joda.github.io/js-joda/

Here’s my final code to get yesterday’s date for a specific time zone

var { ZoneId, ZonedDateTime } = require("@js-joda/core");
require("@js-joda/timezone");

const getYesterdaysDate = () => {
  let zdt = ZonedDateTime.now(ZoneId.of("UTC+05:30"));
  zdt = zdt.minusDays(1);
  let day = zdt.dayOfMonth();
  let month = zdt.monthValue();
  const year = zdt.year();
  if (day < 10) {
    day = "0" + day;
  }
  if (month < 10) {
    month = "0" + month;
  }
  return `${day}-${month}-${year}`;
};
Exit mobile version