Reputation: 2031
On my website, I want to show my local time as Our Time and Visitor time as Your time. Now, I have this JS code:
<script>
function showTime(){
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
var s = date.getSeconds(); // 0 - 59
var session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("our_time").innerText = time;
document.getElementById("our_time").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
</script>
It's showing my Local time.
Now, will I use same code to show the Visitor time or is there anything I need to change?
Upvotes: 0
Views: 328
Reputation: 12954
You need to know your timezone (a list of timezones can be found here) then use it with date.toLocaleTimeString()
like this :
const locale = 'en-US';
const our_timeZone = 'America/Los_Angeles';
// refresh time every second
setInterval(() => {
document.getElementById('our_time').innerHTML = new Date().toLocaleTimeString(locale, { timeStyle: 'long', timeZone: our_timeZone });
document.getElementById('your_time').innerHTML = new Date().toLocaleTimeString(locale, { timeStyle: 'long' });
}, 1);
<p>Our time</p>
<span id="our_time"></span>
<p>Your time</p>
<span id="your_time"></span>
Upvotes: 2
Reputation: 980
maybe your approach is wrong.
a) our time(website time): this should come from a server(and perhaps sync with it in a regular intervel )
b) your time(user's local time): new Date() will do this part since it runs on the client(browser).
this is a sample json data from "http://worldtimeapi.org/api/timezone/America/Argentina/Salta" Oh! it's also free.. hook your ajax call with relevent timezone
{ "week_number":49, "utc_offset":"-03:00",
"utc_datetime":"2019-12-03T11:42:02.994093+00:00",
"unixtime":1575373322, "timezone":"America/Argentina/Salta",
"raw_offset":-10800, "dst_until":null, "dst_offset":0,
"dst_from":null, "dst":false, "day_of_year":337,
"day_of_week":2, "datetime":"2019-12-03T08:42:02.994093-03:00",
"client_ip":"hi hi hi... almost had me there", "abbreviation":"-03" }
also, try this piece of code..
new Date().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
which will give an output
"5:23 PM"
ps: this is just a suggestion..
Upvotes: 1
Reputation: 176
Get timezone of client using
const localDate = new Date(1489199400000);
localDate.getTimeZoneOffset();//time zone offset
then use this value in in Date and get the difference of your time and clients machine time
Upvotes: 0