Clock in different time zones - javascript

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.

Related

jonthornton timepicker : How to get hours and minues

I'm using the jonthornton/jquery-timepicker and could not find the hours and minutes selected.
All I could find was a string output of the form '10:30pm'.
Can the hours and minutes be accessed directly from the control?
I imagined you would be able to do this but could not find it.
The best I've been able to do is what follows, anyone got anything better?
$('#StartTime').on('change', function (timeControl) {
var hoursString;
if (timeControl.target.value.indexOf("am") >= 0) {
hoursString = timeControl.target.value.replace("am", ":00 AM");
}
else {
hoursString = timeControl.target.value.replace("pm", ":00 PM");
}
var oneDate = new Date(Date.parse("2000-01-01 " + hoursString));
var minutes = oneDate.getMinutes();
var hours = oneDate.getHours();
console.log("Hours : " + hours + " | Minutes : " + minutes);
});
The long-standing answer would be Moment.js but it is now considered a legacy project in maintenance mode and not recommended for new projects. There are recommendations on their website for replacements, but bringing in a new dependency for this may be overkill.
The value coming in seems to follow a format which we can rely on to make parsing easy.
Format: H:MMxx
Key:
H = hour, 1-2 characters
MM = minutes, always 2 characters
xx = am or pm, always 2 characters
var timeArray = timeControl.split(':');
var meridiem = timeArray[1].substring(2, 4);
var hours = parseInt(timeArray[0]) + (meridiem === 'pm' ? 12 : 0);
var minutes = parseInt(timeArray[1].substring(0, 2));
var seconds = 0;
// Local time zone, read more: https://stackoverflow.com/a/29297375/5988852
var date = new Date();
date.setHours(hours, minutes, seconds);
// If you want UTC instead
utc = Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
hours,
minutes,
seconds
);
var date = new Date(utc);

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.

Chrome Javascript Date AM | PM

I would like to get this format:
2:18:00 pm
Using the sample code from w3Schools.com below, I can get the correct results from IE and FireFox. But when it comes to Chrome, I get the 24hr clock version where it is simply displayed this way:
14:18:00
In FF
new Date().toLocaleTimeString()
// 2:18:00 pm
function twoDigitPad(number) {
return ("0" + number).slice(-2);
}
function twelveHourTimeString() {
var date = new Date();
var hour = date.getHours();
var min = twoDigitPad(date.getMinutes());
var sec = twoDigitPad(date.getSeconds());
var ampm = hour < 12 ? "am" : "pm";
hour = hour % 12 || 12; // convert to 12-hour format
return hour + ":" + min + ":" + sec + " " + ampm;
}
date.getHours() returns an integer between 0 and 23, which hour % 12 || 12 converts to the 12-hour format.
date.getMinutes() and date.getSeconds() each return an integer, so you'll need to zero-pad those values when they're less than 10. Optionally, hour as well.
Use the following javascript code,
<script type="text/javascript">
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if (curr_hour < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
document.write(curr_hour + ":" + curr_min + ":"
+ curr_sec+ a_p);
</script>
The o/p would be as you expect,2:18:00 PM
Dealing with dates reliably cross-browser is a ball-ache in javascript- I would use the DateFormat library; http://blog.stevenlevithan.com/archives/date-time-format
then as he notes on the page, you can call it like so;
dateFormat(now, "h:MM:ss TT");
There are a few alternatives, but this one seems the most light-weight.

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/

Javascript : Manipulating the status bar to display the date?

I'm trying to write a script to display the current time on a page every minute on the status bar. However nothing shows up on the bar and I have no idea what is wrong.
function display_time(){
var d = new Date();
var h = d.getHours(); // Extract hours
var m = d.getMinutes(); // Extract minutes
var ampm = (h >= 12)?"PM":"AM" // Convert to 12 hr format
if (h > 12) h -= 12; // Next 4 lines; convert time to 12hr format
if (h==0) h = 12;
if (m < 10) m = "0" + m;
var t = h + ':' + m + ' ' + ampm;
defaultStatus = t;
// Repeat function every minute
setTimeout('display_time()', 60000);
}
And Finally I call it as the page loads with <body onload= 'display_time();'>
The time however doesn't show in the status bar of any browser. Any thoughts?
Use window.status instead of defaultStatus. But please be aware that you can't change the status bar in some browsers.

Categories