Parse the datetime string and convert it to UTC using js-joda/core and js-joda/timezone

1.8k views Asked by At

We have to build a website for our client that runs Angular 9+ in the front end and nodejs is the server backend application. Everything working good.

Now, my client wants to support customers initially from the following timezones: Indian Time, Pacific Time, Arizona Time, Mountain Time, Central Time and Eastern Time. We are planning to use @js-joda/core and @js-joda/timezone to accomplish the job.

One of the requirements is to validate the date entered by the user. The date must belong to the current month only. The server is set with UTC timezone. We are thinking about converting the datetime to UTC and then storing it in the (mongodb) database. But we are not sure how we can convert the given date to UTC using js-Joda. We tried using the following code but it doesn't seem to convert.

var jsJoda = require("@js-joda/core");
require("@js-joda/timezone");

var indiaZone = jsJoda.ZoneId.of("Asia/Calcutta");
var localDateTime = jsJoda.LocalDateTime.parse("2021-10-05T23:18:09.905");**//<--user entry date**
var localTime = jsJoda.ZonedDateTime.of(localDateTime, indiaZone);
var utcZoned = jsJoda.ZonedDateTime.of(localTime, jsJoda.ZoneOffset.UTC);
console.log('Current Time in UTC: ' + utcZoned.toString()); 

I expected the date printed would be 5.5 hrs behind but it didn't. Can you please assist if I'm in the right direction and also why the UTC time is showing the same time passed?

2

There are 2 answers

0
Paul Hendriksen On

My issue was that I had a string in eastern standard time that I needed to be converted to UTC using jsJoda.

Solution:

  • date: 2021-05-21
  • hour: 22
  • minute: 00
const jsJoda = require("@js-joda/core");
require('@js-joda/timezone');

let startTime = jsJoda.LocalDateTime.parse(`${date}T${hour}:${minute}`)
    .atZone(jsJoda.ZoneId.of("America/New_York"))
    .withZoneSameInstant(jshourJoda.ZoneId.of("UTC-00:00"));
  • _date: LocalDate { _year: 2021, _month: 5, _day: 22 },
  • _time: LocalTime { _hour: 2, _minute: 0, _second: 0, _nano: 0 }
0
Arvind Kumar Avinash On

You can use ZonedDateTime#withZoneSameInstant to meet the requirement.

Demo:

import {
  LocalDateTime,
  ZoneId,
  ZonedDateTime
} from "@js-joda/core";
import "@js-joda/timezone"; // Automatically adds timezone support

const zoneIdIndia = ZoneId.of("Asia/Kolkata");
const zoneIdUtc = ZoneId.of("Etc/UTC");

const ldt = LocalDateTime.parse("2021-10-05T23:18:09.905");
const zdtIndia = ldt.atZone(zoneIdIndia);
const zdtUtc = zdtIndia.withZoneSameInstant(zoneIdUtc);

console.log(zdtIndia.toString());
console.log(zdtUtc.toString());

Output:

2021-10-05T23:18:09.905+05:30[Asia/Kolkata]
2021-10-05T17:48:09.905Z[Etc/UTC]