Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

javascript - Let's say I want 8:00PM here in my timezone be shown as 4:00PM in another timezone based on the user's timezone, how can I do that?

I will put events on my website and instead of just putting the time of the even in only my timezone, I want it to be automatically converted to the visitor's timezone, maybe from his browser's time or whatever?

Let's say an event starts at 8:00PM here in Europe, but I want it to be shown in the right timezone to someone visiting from Asia. Isn't this possible based on the user's browser or their device's default time?

How can I do that using JS?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have the Time provided as UTC (consider the Date.now() method, with Date object as wrapper), and mostly time would be stored as UTC. a simple .toString() will provide you with a Local Time String. while a .toUTCString() will give back UTC Time

    // Create date object from datetime string
    var date = new Date(Date.now());
    
    //remember Date.now() stores date as milliseconds passed from Unix epoch. Date() converts it into "UTC String"
    // Coverting to local datetime 
    console.log(date.toString());
    
    // Coverting local datetime back to UTC
    console.log(date.toUTCString()); // Tue, 13 Jan 2021      08:46:30 GMT

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...