0

I do have an array of objects coming from API, each of the object containing a property called jpExpiryTime.

    [{   ...
        offer: '',
        jpExpiryTime: 2019-09-26 15:00:00
    },
    {   ...
        offer: '',
        jpExpiryTime: 2019-09-26 15:00:00
    }]

The above date and time value are assigned from the Japan region. I do have a portal which is accessed from India which shows me the list of the above offer data. I want to know if the above offer has expired or not by comparing with the current date and time. I tried the below:

new Date('2019-09-26 15:00:00') > new Date ()

But I find that new Date('2019-09-26 15:00:00') converts the data to IST rather than Japan Standard Time (JST). Could someone shed some light on how to compare a date-time string from one timezone with another date object in another timezone.

Nibin
  • 3,922
  • 2
  • 20
  • 38
  • Possible duplicate of [Convert date to another timezone in JavaScript](https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript) – Nam Tang Sep 24 '19 at 10:28
  • 1
    Include the timezone offset in the date string. For Japan this would be `+0900`, eg. `'2019-09-26 15:00:00 +0900'` – Rory McCrossan Sep 24 '19 at 10:28
  • Even your new Date() will give you date of the timezone it is being accessed so either you can add the offset in the date or you can use moment-js to do the same and then compare the two dates. – Gaurav Singh Sep 24 '19 at 10:37
  • @GauravSingh that is exactly. Both first date with date string and second new Date() will be converted to same timezone of browser being accessed. Then where the req arises of timezone if both are in same TZ then above condition is good to go. – vipul patel Sep 24 '19 at 11:12

2 Answers2

1

You are using normal JS date comparison and conversion. JS is executed client side browser and if its opened in INDIA then it will convert in IST

use Moment js which is very popular.

Convert your date string using timezone and then compare. Everything is available.

isSame, isBefore, isAfter etc.

vipul patel
  • 668
  • 4
  • 7
  • Thanks for your response. I would like to know how to do it using pure javascript rather than using 3rd party libraries. – Nibin Sep 24 '19 at 10:39
  • in your case : new Date('2019-09-26 15:00:00') > new Date () both date will be converted to IST as opened in INIDA. Then comparison would be right only as both are in same TZ. Then where is the case of one would be in one TZ and nother would be in other TZ. – vipul patel Sep 24 '19 at 10:55
0

You can do something like below: First convert the time to "Asia/Tokyo" timezone and then compare.

var japanTime = new Date("2019-09-26 15:00:00").toLocaleString("en-US", {timeZone: "Asia/Tokyo"}); convertedJapanTime = new Date(japanTime); var currentTime=new Date(); var isexpired=currentTime>convertedJapanTime ;

Timezones: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Sarthak Gupta
  • 205
  • 1
  • 15