Home > Back-end >  Find offset in time zone and add/subtract to current time in javascript
Find offset in time zone and add/subtract to current time in javascript

Time:04-24

I am currently working on method in which system has to give automated call to client in their timezone.

Let's say if the client is in "Africa/Blantyre" time zone and I am in "Asia/Jakarta" time zone and the client says to give call at 7 P.M then I would need to store the time in db and system has to call him.

The method which I have thought is to get offset between two timezone ("Africa/Blantyre" and "Asia/Jakarta") and then get 7 P.M in "Asia/Jakarta" , finally add/subtract the offset to the time and that is how I will get 7.PM time for "Africa/Blantyre". But I am not sure how I can implement this?

CodePudding user response:

I think you can fetch the time difference data through this site. As for the method, you can make a json file through which you add all the countries and their time, or via api, you will find it through one of the sites for calculating time differences and calculating Time Zone

https://www.calculator.net/time-zone-calculator.html

CodePudding user response:

You can:

  1. Create a moment for now
  2. Set the timezone to Africa/Blantyre
  3. Set the time to the required local time in Blantyre
  4. Set the timezone to Asia/Jakarta
  5. Display the time in Jakarta

Internally, the moment object uses an instance of the built–in Date object, which has an ECMAScript time value that represents a single moment in time as an offset from the ECMAScript epoch (1 Jan 1970). Changing the timezone just changes calculations for manipulating and displaying the date, it doesn't change the time value.

So after setting the timezone to Africa/Blantyre, setting the time to 19:00 sets it for 19:00 in Blantyre. Changing the timezone to Jakarta also doesn't change the underlying time value, it just means that the generated timestamp is for Jakarta.

So here's some code:

// First get a moment for "now"
let mBlantyre = moment();

// Set the timezone to Africa/Blantyre
mBlantyre.tz('Africa/Blantyre');

// Set the time to 7 pm
mBlantyre.startOf('day').hour(19);

// Copy the moment object
mJakarta = moment(mBlantyre);

// Set the timezone to Asia/Jakarta
mJakarta.tz('Asia/Jakarta');

// Display as timestamps
console.log(
  'Africa/Blantyre: '   mBlantyre.format()  
  '\nAsia/Jakarta   : '   mJakarta.format()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.34/moment-timezone-with-data-10-year-range.min.js"></script>

  • Related