0

when I'm using this format to find the date in American Timezone

new Date().toLocaleString("en-US",{timeZone:"America/LOS_ANGELES"})

I'm getting this output 9/24/2020, 3:47:55 AM which is correct but when I want to change the above output to my local time like this

new Date(""9/24/2020, 3:47:55 AM).toLocaleString("en-US",{timeZone:"Asia/Calcutta"})

still I'm getting the same output as above I want to change the date to my localtime zone i.e., 9/24/2020, 3:47:55 AM but I want to change this output to my localtime zone. can anyone how can I do it??

BIJAY_JHA
  • 21
  • 3
  • I assume that `new Date(""...` is a typo? I've just moved the second " to after the `AM` and got `9/24/2020, 5:13:45 AM` and `9/24/2020, 8:17:55 AM` – ATD Sep 24 '20 at 12:14
  • write Asia/Kolkata, not Asia/Calcutta – BukhariBaBa Sep 24 '20 at 12:15
  • 1
    Trying to use a string in any format other than ISO 8601 is unlikely to give consistent results across browsers and should be avoided. Without time zone or offset information, it is likely to be interpreted in local time. – Heretic Monkey Sep 24 '20 at 12:17
  • The list of valid time zone names is available [on Wikipedia](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). – Heretic Monkey Sep 24 '20 at 12:20
  • Does this answer your question? [How to initialize a JavaScript Date to a particular time zone](https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone) – Heretic Monkey Sep 24 '20 at 12:21
  • @HereticMonkey no, i just want to do the reverse conversion. is this possible with this date format?? – BIJAY_JHA Sep 24 '20 at 12:36
  • According to your code, you seem to want to initialize a date in the "America/LOS_ANGELES" time zone and convert it to the "Asia/Calcutta" time zone. To do that, you'd use the steps in the answers to the posted question to initialize a `Date` object to the "America/LOS_ANGELES" time zone, then use the `toLocaleString` code you already have to format that `Date` object in the "Asia/Calcutta" time zone. – Heretic Monkey Sep 24 '20 at 12:42

2 Answers2

0

The new Date() will show your time-zone as-is.

Save the Date to a variable, THEN do stuff with it:

var d=new Date();
var dls=d.toLocaleString();
var dLA=d.toLocaleString("en-US",{timeZone:"America/LOS_ANGELES"});
var dCal=d.toLocaleString("en-US",{timeZone:"Asia/Calcutta"});

console.log("d=\""+d+"\"");
console.log("dls=\""+dls+"\"");
console.log("dLA=\""+dLA+"\"");
console.log("dCal=\""+dCal+"\"");
.as-console-wrapper { max-height: 100% !important; top: 0; }
iAmOren
  • 2,760
  • 2
  • 11
  • 23
0

For Modern Browsers (Recent MS Edge, Firefox, Safari, Chrome)

Use Intl.DateTimeFormat

If you wanted to get Asia/Calcutta version of the current date/time,

First, create your Date object you want to format

const dateObj = new Date() // Gets the current date and time as an object

Create Formatting Object

You can then create an object that will tell Intl.DateTimeFormat how you want to format the date. This is where you can specify the timeZone to whatever timezone you want.

Here is the MDN reference for what all you can use in the options object

Here is some additional helpful information on the values you can give to those options.

const formattingOptions = { 
  day: 'numeric',
  month: 'numeric', 
  year: 'numeric',
  hour: 'numeric', 
  minute: 'numeric', 
  second: 'numeric', 
  timeZone: 'Asia/Calcutta',
  timeZoneName: 'long'
}

Now we are ready to actually get the formatted time zone string

const calcutta = new Intl.DateTimeFormat('en-us', formattingOptions).format(dateObj)

Your variable calcutta would now contain the date/time string! :)

You can then tinker around with the formatting options until you get the formatted string you want.

In the example above, you would get "4/13/2021, 2:08:46 AM India Standard Time" (the value of calcutta variable).

For Older IE11

This way is much more annoying and verbose. This logic will allow you to force the display of a specific timezone no matter what the user's browser timezone is.

In a nutshell, you convert the date to milliseconds, then subtract the amount hours (in milliseconds) of the offset you want, and then use Intl.DateTimeFormat with the option of timeZone: UTC and then append your own Timezone string to that.

Here is an example that worked for me on a project recently

On this project I was in the USA and was dealing with displaying a date that needed to always be in Central Time (Daylight Savings Time responsive) no matter what the end users time zone is.

  1. First we'll make up the date we want to test as a date object (i.e. currentDateObj)
  2. Then, figure out if the timezone I'm converting to is in Daylight Savings Time or not. In this example we'll deal with Central Time ('America/Chicago'). Chicago's Central Time switches between Central Daylight Time (UTC-5) and Central Standard Time (UTC-6). If you want to just always display a specific time zone that doesn't care about Daylight savings, skip to step 7.
  3. Look up a reference date where I know that the date is not in Daylight Savings time (for example, a date in January will be in Central Standard Time) and use getTimezoneOffset on that reference date.
  4. Do getTimezoneOffset() on the currentDateObj and store that in a variable.
  5. Depending upon the target timezone I'm dealing with (in this case Central Standard Time will have a value greater than Central Daylight Time for getTimezoneOffset), check to see if the timezone offset for the referenceDate is > the currentDate's timezone offset (see Note 1 below for more information on this)
  6. We need to calculate the number of milliseconds to subtract off the UTC date (in milliseconds) to get the date & time we want. If the date is:
  • Within Daylight Savings (referenceDateOffset > currentDateOffset), we're dealing with UTC-5 we'll need to figure out what 5 hours is in milliseconds. 5 hours * 60 mins / hr * 60 secs per min * 1000 milliseconds per sec = 18000000 milliseconds.
  • Within Standard Time (referenceDateOffset is not > currentDateOffset), we're dealing with UTC-6 we'll need to figure out what 6 hours is in milliseconds. 6 hours * 60 mins / hr * 60 secs per min * 1000 milliseconds per sec = 21600000 milliseconds.
  1. Let's say we're dealing with Chicago in Daylight Savings Time. We get the currentDate in milliseconds from Unix Epoch (currentDateObj.getTime() or currentDateObj.valueOf()) and (since we want UTC minus 5 (UTC-5)) then subtract 5 hours worth of milliseconds (18000000) and save that result to a variable
  2. Create up a new Date object from that new variable we created in step 7.
  3. Then use the Intl.DateTimeFormat with a timeZone option of UTC (and various other options) and append the Time Zone Name yourself at the end of the string.

Code Example

Here is a code example that detects if the date should be shown in Daylight or Standard Time:

const currentDateObj = new Date() //step 1

const formattingObj = { 
      year: '2-digit',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      timeZone: 'UTC',
      hour12: true
} // used in step 9

const centralTimeOffsetInfo = getCurrentCentralTimeOffsetInfo(currentDateObj)
// function declaration is below; returns an object like { millis: 18000000, timeZone: 'CDT' } 

const currentDateInMS = currentDateObj.getTime() // step 7
const adjustedToCentralDateMillis = currentDateInMS - centralTimeOffsetInfo['millis'] // step 7
// You would be adding above if you were on a time zone offset that is positive - like UTC+3 for example


const centralTimeDateObj = new Date(adjustedToCentralDateMillis) // step 8
      
centralTimeString = Intl.DateTimeFormat('en-US', formattingObj).format(centralTimeDateObj) + centralTimeOffsetInfo['timeZone'] // step 9

console.log("Central Time String: ", centralTimeString)

// This function contains steps 2 - first 6
function getCurrentCentralTimeOffsetInfo(dateObj) {
   const mutableDateObj = new Date(dateObj)
   mutableDateObj.setMonth(0)
   const janOffset = mutableDateObj.getTimezoneOffset() // This offset gives me a reference to a Standard Time offset for the current year that the date is in. 
   const currentOffset = dateObj.getTimezoneOffset() 

   if (janOffset > currentOffset) {
      // it is Daylight Savings Time (CDT) and so offset is - 5 hours
      // 6 hours in milliseconds = 60000 (millis in 1 min) * 60 mins in 1 hr * 5 hrs = 18000000 millis
      return {
         millis: 18000000,
         timeZone: " CDT"
      }
   } else {
      // It is not Daylight Savings Time; It is Standard Time, so offset is - 6 hours
      // 6 hours in milliseconds = 60000 (millis in 1 min) * 60 mins in 1 hr * 6 hrs = 21600000 millis
      return {
         millis: 21600000,
         timeZone: " CST"
      }
   }
}


Note 1 - Logic Explanation

Chicago's Central Time switches between Central Daylight Time aka "CDT" (UTC-5) and Central Standard Time aka "CST" (UTC-6).

The integer returned from the getTimezoneOffset() method is in minutes.

getTimezoneOffset returns a positive integer for for negative UTC offsets (CDT = UTC-5 = 5hrs * 60 mins = 300) and a negative integer for positive UTC offsets (UTC+3 = -3hrs * 60 mins = -180). Reference

In this case, the offset for UTC-6 (CDT) = 360 and the offset for UTC-5 = 300

So, you can then just check if the referenceDate's offset is > the currentDate offset

if (refDateOffset > currentDateOffset) { 
  // refDateOffset = 360
  // currentDateOffset = 300
  // This means that the current Date for Central Time is using Central Daylight Time (CDT) because its offset is less than the Standard Time refDateOffset.
  return {
    millis: (5*60*60*1000), // number of milliseconds in 5 hours (UTC-5) to subtract from the UTC milliseconds in step 7
    timeZone: " CDT" // timezone stub to use in step 9
  }
} else {
  // refDateOffset = 360
  // currentDateOffset = 360
  // currentDateOffset is equal to the refDateOffset so:
  // refDateOffset is not `>` currentDateOffset
  // The currentDate is in Central Standard Time
  return {
    millis: (6*60*60*1000), // number of milliseconds in 6 hours (UTC-6) to subtract from the UTC milliseconds in step 7
    timeZone: " CST" // timezone stub to use in step 9
  }

}

Caveat: This logic above only works if the end user browser is in a timezone that has the same Daylight Savings Time switching as Central Time (would work for most USA timezones). You'd have to add additional logic that figures out if the currentDate falls between the Daylight Savings time dates each year for that time zone.

growingdev
  • 11
  • 1