How to show Your time and Our time clock using JavaScript? - javascript

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?

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>

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..

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

Related

Javascript time function not displaying correctly

I have a function to display the time from javascript with a two minute delay. The only problem is that when the time is for example, 2:00pm, the function displays 2:0-2pm instead of 1:58pm.
Here is the code below:
function startTime() {
var today = new Date();
var h = today.getHours();
var m = eval(today.getMinutes()-2); // needs eval function
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var time = h>=12?" PM":" AM" // am or pm
h = h % 12;
h = h ? h : 12; // the hour '0' should be '12'
m = m < 10 ? ''+m : m;
document.getElementById('txt').innerHTML =
"Time: " + h + ":" + m + ":" + s + time;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<body onload="startTime()">
<div id="txt"></div>
Your problem is that you're subtracting 2 minutes without considering that you're dealing with time, not just numbers. Also, your function can be a lot more concise.
A simple solution is to subtract 2 minutes from the date before formatting it. That will also adjust the hours and allow for daylight saving where it's observed. Where the changeover time is 02:00 and going into daylight saving, 2 minutes before 03:00 is 01:58. Similarly when coming out of daylight saving.
Consider:
function get2MinsAgo() {
function z(n){return (n<10? '0' : '') + n}
var d = new Date();
d.setMinutes(d.getMinutes() - 2);
return (d.getHours() % 12 || 12) + ':' +
z(d.getMinutes()) + ':' +
z(d.getSeconds()) + ' ' +
(d.getHours() < 12? 'AM' : 'PM');
}
function showTime(){
// Run just after next full second
var lag = 1020 - new Date()%1000;
document.getElementById('timeText').textContent = get2MinsAgo();
setTimeout(showTime, lag);
}
showTime()
<div>Two minutes ago was <span id="timeText"></span></div>
I suspect that it is because at 2:00pm or any time on the hour the "getMinutes()" function will return with 00 minutes. So that when you subtract two from that it sets itself to -2 rather than 58.

How to get current time in a format hh:mm AM/PM in Javascript?

I have a Javascript in which I need to paste the current time in a format HH:MM AM/PM. There's one catch - I need to put the time that starts in two hours from now, so for example, instead of 7:23PM I need to put 9:23PM, etc.
I tried to do something like: var dateFormat = new Date("hh:mm a") but it didn't work. I also tried to use:
var today = new Date();
var time = today.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
alert(time);
but all I've seen was e.g. 18:23 instead of 6:23 PM (probably because of toLocaleTimeString() and my location in Europe) - maybe there's some unified way to do that that will work all around the World?. Also, I don't know exactly how to add the 2 hours to the final result. Can you help me?
Thanks!
You can convert the current time to 12 hour format with a one liner
new Date().toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
And to add two hours to your current time
Date.now() + 2 * 60 * 60 * 1000
So you can do it in a simple one line as:
new Date(Date.now() + 2 * 60 * 60 * 1000).toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
Use Date methods to set and retrieve time and construct a time string, something along the lines of the snippet.
[edit] Just for fun: added a more generic approach, using 2 Date.prototype extensions.
var now = new Date();
now.setHours(now.getHours()+2);
var isPM = now.getHours() >= 12;
var isMidday = now.getHours() == 12;
var result = document.querySelector('#result');
var time = [now.getHours() - (isPM && !isMidday ? 12 : 0),
now.getMinutes(),
now.getSeconds() || '00'].join(':') +
(isPM ? ' pm' : 'am');
result.innerHTML = 'the current time plus two hours = '+ time;
// a more generic approach: extend Date
Date.prototype.addTime = addTime;
Date.prototype.showTime = showTime;
result.innerHTML += '<h4>using Date.prototype extensions</h4>';
result.innerHTML += 'the current time plus twenty minutes = '+
new Date().addTime({minutes: 20}).showTime();
result.innerHTML += '<br>the current time plus one hour and twenty minutes = '+
new Date().addTime({hours: 1, minutes: 20}).showTime();
result.innerHTML += '<br>the current time <i>minus</i> two hours (format military) = '+
new Date().addTime({hours: -2}).showTime(true);
result.innerHTML += '<br>the current time plus ten minutes (format military) = '+
new Date().addTime({minutes: 10}).showTime(true);
function addTime(values) {
for (var l in values) {
var unit = l.substr(0,1).toUpperCase() + l.substr(1);
this['set' + unit](this['get' + unit]() + values[l]);
}
return this;
}
function showTime(military) {
var zeroPad = function () {
return this < 10 ? '0' + this : this;
};
if (military) {
return [ zeroPad.call(this.getHours()),
zeroPad.call(this.getMinutes()),
zeroPad.call(this.getSeconds()) ].join(':');
}
var isPM = this.getHours() >= 12;
var isMidday = this.getHours() == 12;
return time = [ zeroPad.call(this.getHours() - (isPM && !isMidday ? 12 : 0)),
zeroPad.call(this.getMinutes()),
zeroPad.call(this.getSeconds()) ].join(':') +
(isPM ? ' pm' : ' am');
}
<div id="result"></div>
Simply, you can do this
const date = new Date()
const options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
const time = new Intl.DateTimeFormat('en-US', options).format(date)
console.log(time)
For more details, you can refer to the MDN docs regarding the same.
Note that the accepted answer, while good, does not appear to meet the format requirement of: HH:MM AM/PM. It returns midnight as "0:0:38am" and so forth.
There are many ways one could do this and one alternative is shown below. Click the "Run Code Snippet" to test.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Clock</title>
</head>
<body>
<span id="clock" style="font-family: monospace; font-size: 48px; background-color: black; color: lime; padding: 10px;">00:00:00 AM</span>
<script type="text/javascript">
function getTime( ) {
var d = new Date( );
d.setHours( d.getHours() + 2 ); // offset from local time
var h = (d.getHours() % 12) || 12; // show midnight & noon as 12
return (
( h < 10 ? '0' : '') + h +
( d.getMinutes() < 10 ? ':0' : ':') + d.getMinutes() +
// optional seconds display
// ( d.getSeconds() < 10 ? ':0' : ':') + d.getSeconds() +
( d.getHours() < 12 ? ' AM' : ' PM' )
);
}
var clock = document.getElementById('clock');
setInterval( function() { clock.innerHTML = getTime(); }, 1000 );
</script>
</body>
</html>

Leading zeros in minutes

I created a clock to be placed in the header of my website. The time is not displaying a zero for minutes < 10. For example if the time is 10:50, it will only show 10:5 ,I found a solution but unsure of how to implement it. Also if there is a better method please share.
var current;
window.onload = function () {
current = new Date();
document.getElementById("clock").innerHTML = current.getHours() + ":" + current.getMinutes();
This is what I need
if (minutes < 10)
minutes = "0" + minutes
and this is the container for my clock
<span id="clock">&nbsp</span>
You can just grab the first 5 characters of the time string.
(new Date()).toTimeString().substr(0,5)
Since you're likely to run into presentational issues in the future along the same lines, I'd recommend picking a favorite string formatting function for Javascript.
Some examples:
http://www.masterdata.se/r/string_format_for_javascript/
http://www.diveintojavascript.com/projects/javascript-sprintf
Then you can do something like "{0:00}:{1:00}".format(current.getHours(), current.getMinutes()) or even better,
var d = new Date();
var s = d.format("hh:mm:ss tt");
// Result: "02:28:06 PM"
And what is your issue?
var minutes = (current.getMinutes() < 10? '0' : '') + current.getMinutes();
Since you'll have the same problem with hours, wrap it in a small utility function:
function pad(var value) {
if(value < 10) {
return '0' + value;
} else {
return value;
}
}
And later simply:
pad(current.getHours()) + ":" + pad(current.getMinutes())
I like this way of doing things...
Javascript add leading zeroes to date
const d = new Date();
const date = (`0${d.getMinutes()}`).slice(-2);
console.log(date); // 09;
2019 Update:
But I now prefer
const d = new Date();
const date = String(d.getMinutes()).padStart(2, '0');
console.log(date); // 09;
I tried this way. It's not brief but it works.
var dt = new Date();
if (parseInt(dt.getMinutes()) < 10) {minutes = "0" + dt.getMinutes();} else minutes = dt.getMinutes();
if (parseInt(dt.getSeconds()) < 10) {seconds = "0" + dt.getSeconds();} else seconds = dt.getSeconds();
var time = dt.getHours() + ":" + minutes + ":" + seconds;
document.write("Now is:" + time);
//Result: Now is: 22:47:00
I hope it will be useful
Today I'm using .toLocaleTimeString(), which by default returns something like "08:30:00" - based on the users browser locale.
you can force a locale like this:
(new Date()).toLocaleTimeString("de-DE")
and way more interesting is the 2nd options-parameter:
(new Date()).toLocaleTimeString(
"de-DE",
{
hours: "2-digit",
minutes: "2-digit",
seconds: "2-digit",
}
)
ifyou remove e.g. the seconds from the options, it will print only the hours and minutes.
So based on the original question, today I would use this:
var current;
window.onload = function () {
current = new Date();
document.getElementById("clock")
.innerHTML = current.toLocaleTimeString(
navigator.language,
{
hours: "2-digit",
minute: "2-digit"
}
);
and a bit cleaner/shorter:
var current;
var timeOptions = {
hours: "2-digit",
minute: "2-digit"
};
window.onload = function () {
current = new Date();
document
.getElementById("clock")
.innerHTML = current.toLocaleTimeString(navigator.language, timeOptions);

Clock in different time zones

I am trying to create two clocks on a website that says two times on it. One from London and the other from New York.
I have been able to create a clock that reads the current time on my computer but i'm not sure how to place a time zone into this.
The code I have so far is:
<script type="text/javascript" language="javascript">
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12
} else if (h > 12) {
h = h - 12;
diem = "PM";
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById ("clockDisplay");
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
setTimeout ('renderTime()', 1000);
}
renderTime();
</script>
This is being applied to a CSS style I have created so I can have the clock in a specific typeface.
To do this properly, you will need a time zone database, such as one of the ones I listed here.
All of the other answers to this question are making the mistake in thinking that a "time zone" and a "time zone offset" are the same thing. They are not. For example, the time zone for London is Europe/London, which can have either a +0 or +1 offset depending on what time of year it is. The time zone for New York is America/New_York, which can have either a -5 or -4 offset based on a completely different set of dates than London.
You might want to look at moment-timezone:
moment().tz("America/New_York").format()
currentTime.getTimezoneOffset() will give you the time difference between Greenwich Mean Time (GMT) and local time, in minutes.
You can use the value to calculate time in required timezone.
You can add or subtract hours from your date with
currentTime.setHours(currentTime.getHours()+offset);
where offset is any number of hours.
I updated the jsfiddle with that line and the function so that it accepts a parameter for the offset. This is not the UTC offset, just how many hours to add from the system time. You can get the current UTC offset by currentTime.getTimezoneOffset()/60
Demo
Check out http://www.datejs.com/ it handles dates and timezones nicely
if you check out the demo, in the text box, put 1 GMT vs 1 MST or 1 EST and it will pop out a nice date for you wrt/ that time zone
Thank you everyone for your help. It was all getting a bit confusing but I found a good example here which is how I ended up working it out. Check out example 4: http://www.ajaxupdates.com/jclock-jquery-clock-plugin/
Hope it's useful for someone else!
I use on m php website the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
<?php
echo " var z = '".strftime("%Z",strtotime("now"))."';\n";
?>
var d = new Date();
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var offset = -8;
if(z == "PDT") offset = -7;
var currentTime = new Date(utc + (3600000*offset));
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = ( currentHours == 0 ) ? 12 : currentHours;
var currentTimeString = currentHours + ":" + currentMinutes + ": " + timeOfDay + " " + z;
$('td#clock').html(currentTimeString);
setTimeout("getStatus()",5000);
}
</script>
Where i use a table, so this will fill
<table><tr><td id='clock'></td></tr></table>
with the time from Los Angeles (PDT or PST) however my server also runs on that time so passing the strftime from your server might not produce the same effect. But as stated this was my resolve to get a working time in a other zone.

I'd like to create a javascript clock for a specific time zone

I'd like to add a clock to my web site, displaying the time in the Central time zone. I have included the code I have thus far. I want to use this to tell users when other tools on my web site will be active (they are not active during the night in the Central time zone). Does anyone know how to (1) lock this to central time; and (2) perhaps turn it a red color from 8:00 p.m. - 7:30 a.m. (indicating the tools are turned off)?
<script type="text/javascript">
function GetClock(){
d = new Date();
nhour = d.getHours();
nmin = d.getMinutes();
if(nhour == 0) {ap = " AM";nhour = 12;}
else if(nhour <= 11) {ap = " AM";}
else if(nhour == 12) {ap = " PM";}
else if(nhour >= 13) {ap = " PM";nhour -= 12;}
if(nmin <= 9) {nmin = "0" +nmin;}
document.getElementById('clockbox').innerHTML=""+nhour+":"+nmin+ap+"";
setTimeout("GetClock()", 1000);
}
window.onload=GetClock;
</script>
<div id="clockbox"></div>
If you create a local date object, it will be in the timezone of the local system (whatever that might be set to, which might not be the actual local time zone). Date objects have a getTimezoneOffset method that returns a number in minutes that, if added to the local date object, sets it to UTC (essentially GMT). You can then subtract the offset for "central time" (whatever that might be) to get a time in that timezone.
You can then use that date object for times in that zone.
If the timezone is the US Central time zone, the standard offset is -6 hours, the daylight saving offset is -5 hours. A function that returns a date object with a specific offset is:
/* Create a date object with the desired offset.
Offset is the time that must be added to local time to get
UTC, so if time zone is -6hrs, offset is +360. If time zone
is +10hrs, offset is -600.
*/
function getOffsetDate(offsetInMintues) {
// Get local date object
var d = new Date();
// Add local time zone offset to get UTC and
// Subtract offset to get desired zone
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - offsetInMintues);
return d;
}
Give it the appropriate offset and it will return a date object with that offset. To get US standard central time:
var centralDate = getOffsetDate(360);
For US central daylight saving time:
var centralDSTDate = getOffsetDate(300);
To do something between specific times, you can do something like:
var h = centralDate.getHours();
var m = centralDate.getMinutes();
if (h >= 20 ||
h <7 ||
(h == 7 && m <= 30) {
// the time is between 20:00 and 07:30 the following day.
}
The Date object can be modified to any value you like and will be corrected automatically.
"windTheClock(2);" sets time zone offset to +2 UTC.
<script type="text/javascript">
function addLeadingZero(n) {
if (n < 10) {
n = "0" + n;
}
return n;
}
function windTheClock(timeZoneOffset)
{
var d = new Date();
d.setHours(d.getUTCHours() + timeZoneOffset); // set time zone offset
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
h = addLeadingZero(h);
m = addLeadingZero(m);
s = addLeadingZero(s);
document.all["clock"].innerHTML = h + ":" + m + ":" + s;
setTimeout(function(){ windTheClock(timeZoneOffset) }, 1000);
}
window.onload = function() {
windTheClock(2);
}
</script>
<div id="clock"></div>
version w/ am/pm
function addLeadingZero(n) {
return n < 10 ? '0' + n : n;
}
function windTheClock(timeZoneOffset)
{
var d = new Date();
d.setHours(d.getUTCHours() + timeZoneOffset); // set time zone offset
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var ampm = h >= 12 ? 'pm' : 'am';
h = h % 12;
h = h ? h : 12; // replace '0' w/ '12'
h = addLeadingZero(h);
m = addLeadingZero(m);
s = addLeadingZero(s);
document.all["clock"].innerHTML = h + ':' + m + ':' + s
+ ' ' + ampm;
setTimeout(function(){ windTheClock(timeZoneOffset) }, 1000);
}
window.onload = function() {
windTheClock(2);
}
https://jsfiddle.net/dzyubak/rae8j6xn/

Categories