0

How can i check if in another specific location now is daylight saving time using only native javascript?

For example, if i am based in Hong Kong, how can I use js to check if in New York or London currently is daylight saving time or not?

I have checked some posts like e. g. How to check if the DST (Daylight Saving Time) is in effect and if it is what's the offset?

It looks like it works if my base and target location are the same. But what if I want to check a different location, like ny/london?

My code:

function isDaylightSaving() {
    const today = new Date();
    const jan = new Date(today.getFullYear(), 0, 1);
    const jul = new Date(today.getFullYear(), 6, 1);
    return today.getTimezoneOffset() < Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
  1. If my local PC clock changes to Hong Kong time zone, it will always get false
  2. If my local PC clock changes to New York or London time zone, it will get true (given in April is daylight saving time)
digijay
  • 1,329
  • 4
  • 15
  • 25
coder_ll
  • 29
  • 2
  • 2
    the browser / JS does not know this information. You'd have to find a webservice / API which would provide it, and make an ajax request – ADyson Apr 11 '18 at 15:00
  • Thanks, that is the approach i finally use, to call a webservice – coder_ll Apr 12 '18 at 14:44

1 Answers1

0

problem is that JS doesnt know anything about DST. you would have to create a table of countries and their DST start/end, and then supply js with country name.

you can get data from call to site, which will tell you which country user is in (countries in same timezone doesnt have same DST rules, so using only clock conversion wont work in all cases).

How to get client's IP address using JavaScript only? *APIs listed here retrieve also county

then you got this api:

http://services.timeanddate.com/api/doc/current/srv-dstlist.html

from which you can retrieve data about DST.

depending on what you want to do, you will have to choose different approach, but those apis should give you access to all data you need, retrievable and useable with pure javascript.

Round-Sliced
  • 61
  • 10