pl2ern4
pl2ern4

Reputation: 375

Save date in given timezone

I'm using react-datePicker library which takes new Date() as input. Here I'm taking input date, time & timezone. How I can save this in the backend such that if the user selects the date Feb 10 2024 & time 02:00 & timezone BST irrespective of the location user should see the date as Feb 10 2024 02:00 BST in Date Object?

Right now new Date("2024-02-10T03:00:00.000Z") is giving me Sat Feb 10 2024 08:30:00 GMT+0530 (India Standard Time). I want this should be `Sat Feb 10 2024 08:30:00 GMT+0100 (British Summer Time). I already tried:

const tzname = "Europe/London";
const longOffsetFormatter = new Intl.DateTimeFormat("en-US", {timeZone: tzname ,timeZoneName: "longOffset"});
const longOffsetString = longOffsetFormatter.format(new Date("2024-02-10T03:00:00.000")); 

Moment.js could be helpful but it is legacy so not advised to use.

How I can save the Date based on the passed timezone instead local timezone?

Upvotes: 0

Views: 200

Answers (1)

Hoppix
Hoppix

Reputation: 660

Try using luxon which provide modern alternatives to Moment.js and offer support for timezones.

const { DateTime } = require('luxon');

// User input values
const selectedDate = '2024-02-10'; // Example date
const selectedTime = '02:00'; // Example time

// Combine date and time into a single string
const dateTimeString = `${selectedDate}T${selectedTime}:00.000`;

// Create a DateTime object with the user-selected values in UTC
const utcDateTime = DateTime.fromISO(dateTimeString);

// Convert the UTC DateTime object to the local timezone
const localDateTime = utcDateTime.setZone('local');

// Format the local DateTime object in the desired format
const output = localDateTime.toLocaleString({
  weekday: 'short',
  month: 'long',
  day: 'numeric',
  year: 'numeric',
  hour: 'numeric',
  minute: '2-digit',
});

console.log(output); 

The output is now

Sat, February 10, 2024, 2:00 AM // Or
Feb 10 2024 02:00 BST

Upvotes: 1

Related Questions