We have a lot of data where dates are saved with the time component and these dates are saved from different time zones. For example, if we save "1st July 2022" in IST, in the database it is saved as "2022-06-30T18:30:00.000Z". But if we save the same date in EST, it is saved as "2022-07-01T04:00:00.000Z". Like this, we have data from a couple more time zones like the Central and Pacific timezone. Now the task is to show 1st July for all these time zones. Naturally, I browsed the internet for a solid foolproof answer, but couldn't get any. This one is the best I could come up with. But this is not foolproof. So need one logic that will work across any timezone.
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
CodePudding user response:
You can use Date.toLocaleDateString()
to show the date in the user agent's timezone.
Using a dateStyle of 'long' will show the date using a d MMM yyyy
format, e.g. 1 July 2022.
function formatAsLocalDate(timestamp) {
const dt = new Date(timestamp);
return dt.toLocaleDateString('default', { dateStyle: "long" });
}
// This would be the date stored to the database...
const utcDate = new Date(2022, 06, 01).toISOString();
console.log('UTC date:', utcDate);
console.log('Local date:', formatAsLocalDate(utcDate))
.as-console-wrapper { max-height: 100% !important; }
CodePudding user response:
Working with time zones can be tricky. It is best to use a JavaScript date library that can help you with date parsing, formatting and time zone translation.
It can be subjective as to which library to choose. I could recommend Day.js. Luxon is also very good (but has Monday as the first day-of-the-week which can't be changed).
An example with Day.js looks like the code sample below. The dayjs.tz.guess() function can be used to try to get the time zone from the user's browser.
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend( utc );
dayjs.extend( timezone );
const YOUR_ISO8601_DATE = '2022-06-30T00:20:00.000Z';
const DESIRED_TIME_ZONE_LOCATION = dayjs.tz.guess(); // e.g. 'Indian/Mauritius';
let localDate = dayjs( YOUR_ISO8601_DATE ).tz( DESIRED_TIME_ZONE_LOCATION ).format( 'YYYY-MM-DD' );
As an aside: An UTC offset does not provide enough information for you to know how to translate a time from GMT to a desired time zone in a specific location. Time zone rules (e.g. when Daylight Savings Time/Summer Time begins and ends) are determined by governments rather than operating systems. A JavaScript date library along with use of IANA time zone database time zones (e.g. "America/New_York") could allow you to reflect time zone offset rules in your dates for specific locations.