0
const date = new Date(new Date().toLocaleString("en-US", { timeZone: "IST" }));
date.setDate(date.getDate() + offSet);
console.log(date.toISOString().split("T")[0])  

I am using this code in reactjs to get the date in IST irrespective of the current timezone. Its working fine but in logs (sentry) I saw, sometimes it is throwing this error:

RangeError new DateTimeFormat(native) Unhandled error "Expected Area/Location(/Location)* for time zone", got IST

Can you suggest what might be the possible issue?

Note: This issue is seen on chrome, firefox, and edge

2Cool
  • 31
  • 4

1 Answers1

0

The reason for the error is that the value for timeZone should be an IANA representative location, not a civil timezone abbreviation. For IST (I assume that's India Standard Time) use Asia/Kolkata:

console.log('Current date in India: ' + new Date().toLocaleDateString('en-gb',{timeZone:'Asia/Kolkata'}));

It seems you want the date in YYYY-MM-DD format. You can do that using a language code that produces the required result, e.g. en-CA:

console.log('Current date in India: ' + new Date().toLocaleDateString('en-CA',{timeZone:'Asia/Kolkata'}));

However, that leaves you at the mercy of whatever an implementation thinks the format for en-CA should be. Far better to get the parts and format them yourself:

function getIndiaDate(date = new Date()) {
  let {year, month, day} = new Intl.DateTimeFormat('en',{
    timeZone: 'Asia/Kolkata',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).formatToParts(date)
    .reduce((acc, part) => {
      acc[part.type] = part.value;
      return acc;
    }, Object.create(null));
  return `${year}-${month}-${day}`;
}

console.log(getIndiaDate());

A library might help. See How to format a JavaScript date.

Note that doing date calculations using local methods (e.g. get/setDate) uses the host regional settings for offsets, including daylight saving. For timezone and location aware calculations, you really should use a library that supports them. The proposed Temporal object should address that issue by allowing a Date object to have an associated set of offset rules based on IANA representative location.

RobG
  • 124,520
  • 28
  • 153
  • 188