Live Digital clock with timezones - javascript

I have a digital clock that is running and it works great but I want to have multiple clocks running with different timezones. I am on the west coast and I would like the time to be different when people look at it in different timezones. How can I accomplish this?
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "AM";
if (hours > 12) {
hours = hours - 12;
meridiem = "PM";
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000);
});

To get the time in any timezone based on the current system time (which might be wrong, but that may not really matter), create a Date and just adjust the UTC time values by the required offset, then use UTC methods to build your formatted string.
e.g.
/* Return a time string in h:m:s a/p format
**
** #param {number} offsetInMinutes - offset of required timezone in minutes
** #returns {string} formatted time string
*/
function getTimeInZone(offsetInMinutes) {
function z(n) {return (n<10?'0':'') + n;}
var d = new Date();
d.setUTCMinutes(d.getUTCMinutes() + offsetInMinutes);
var h = d.getUTCHours();
return z(h%12||12) + ':' + z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' + (h<12? 'am' : 'pm');
}
// Time at UTC-08:00
document.write(getTimeInZone(-480));
You say you're "on the west coast", but not of where, so I'll assume USA where the likely timezone offset is UTC-08:00 (-480 minutes). So to always show the time in that timezone (with the usual caveat that the system clock may not be correct), you'd do:
getTimeInZone(-480);
Also note that innerText is a IE proprietary property and not supported in all browsers.

Related

How do I pull javascript time other than from the user's device

I use a script that coverts Earth Time into an in-game time for a game (Eorzea Time). The script that was originally written is here.
My issue is that this pulls the Earth Time from the user's device clock. So if the clock is not correct on their device the conversion to Eorzea time is not accurate.
I'd like to pull Earth Time from a clock that is guaranteed to be accurate. I've been unable to figure out how to do this.
As an example. If you view this script alongside this site (www.ffxivclock.com) and change your time by even a minute or two...the jsfiddle clock will be off while the ffxivclock.com time will still be correct.
var E_TIME = 20.5714285714;
var global = {
utcTime: null,
eorzeaTime: null
};
window.setInterval(updateClock, Math.floor(1000 * 60 / E_TIME));
function updateClock() {
global.utcTime = new Date().getTime();
var eo_timestamp = Math.floor(global.utcTime * E_TIME);
global.eorzeaTime = new Date();
global.eorzeaTime.setTime(eo_timestamp);
showTime();
}
function showTime() {
var d = new Date();
d.setTime(global.eorzeaTime);
var eTime = document.getElementById('e-time');
var hours = d.getUTCHours();
var ampm = hours > 11 ? "PM" : "AM";
if(hours > 12)
hours -= 12;
hours = padLeft(hours);
var minutes = d.getUTCMinutes();
minutes = padLeft(minutes);
eTime.innerHTML = hours + ":" + minutes + " " + ampm;
}
function padLeft(val){
var str = "" + val;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
updateClock();

Converting specific military time with Angular and Javascript filter

I see that I various times like
01:45
//and
15:00
I assume that date is HH:MM in military ?
While have I seen some advanced functions then parse sentences and even some using the seconds like HH:MM:SS , I am wanting a simple and accurate way of getting the HH:MM
So I assume 15:00 is 3:00 ?
This function below is not going to work because I already have ":"
so below assumed HHMM right? when I believe I need HH:MM to be parsed ?
var getTravelTimeFormatted = function (str) {
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
Update
Ok, I assume that 15:00 is 3:00 , right?
So i stripped out the incoming ":" and then add it back
problem is the result is 25.0 so what does that mean?
var getTravelTimeFormatted = function (str) {
str = str.replace(/:/g,'');
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
console.log(getTravelTimeFormatted('15:00'));
Given a string HH:MM you can just split then subtract 12 hours. Here's a naive solution that doesn't check for invalid input.
function TwelveHourFormat(time) {
var dtParts = time.split(":");
var hours = dtParts[0];
var minutes = dtParts[1];
var suffix = "AM";
if (hours > 12) {
hours = hours - 12;
suffix = "PM";
}
else if (hours == "00") {
hours = 12;
suffix = "AM";
}
else if (hours == "12") {
suffix = "PM";
}
return (hours + ":" + minutes + " " + suffix);
}
This is a duplicate of Converting 24 hour time to 12 hour time w/ AM & PM using Javascript. Jasen's answer is fine, and more concise than the duplicate, but the function can be a little more concise:
/* Convert time in 24 hour hh:mm format to 12 hour h:mm ap format
** #param {string} time - in hh:mm format (e.g. 14:30)
** #returns {string} time in 12 hour format (e.g. 2:30 PM)
*/
function to12HourTime(time) {
var b = time.split(/\D/);
return (b[0]%12 || 12) + ':' + b[1] +
(b[0]<11? ' AM' : ' PM');
}
// Some tests
['23:15','2:15','03:15','00:30'].forEach(function(v) {
console.log(v + ' => ' + to12HourTime(v));
});

Page last modified using Javascript with 12 hour clock showing am or pm

I'm trying to create a script in Javascript that shows when a page was last modified, which returns the date, time, in am or pm format, of modification.
Clearly I am doing something wrong. I can't get the script to run, and it will be in my function AmPm. Can someone please help?
// Javascript code for page modification
// Shows the date, time, am or pm, of modification.
// This section sets the date of modification
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "." + (modiDate.getMonth() + 1) + "." + modiDate.getFullYear();
return showAs
}
// This section sets the time of modification
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
// This section writes the above in the document
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
// This section decides if its am or pm
function AmPm() {
var hours = new Date().getHours();
var hours = (hours + 24 - 2) % 24;
var mid = 'AM';
if (hours == 0) { // At 00 hours (midnight) we need to display 12 am
hours = 12;
} else if (hours > 12) // At 12pm (Midday) we need to display 12 pm
{
hours = hours % 12;
mid = 'PM';
}
}
var mid = //This is where I am stuck!!
return AmPm
document.write("This webpage was last edited on: ");
document.write(lastModified() + " at " + GetTime() + AmPm());
document.write("");
document.write(" NZ Daylight Savings Time.");
document.write("");
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}

Date formating gives different results in Chrome than in other browsers?

I want to show the time in a readable format. So I am using the below js code. But the output is different in Chrome and IE. How do I change the code to give the same output across all the browsers ?
The output in IE : 12:46 am
In Chrome : 6:16 am
Time zone is : UTC +05:30
var unReadableDate = "2016-01-25T00:46:00";
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
Can you please try replacing this
var unReadableDate = "2012-06-25T00:46:00.000Z"
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
Converting a UTC format string to a date using Javascript Date constructor is not reliable. If you want to tackle timezone issues with date you should use moment.js. To understand more you can use below link.
Javascript Date issue
OR simple way to resolve the issue is pass individual arguments in the date instead of complete string. To understand more you can use below link
DateTime UTC
Your problem is that your date string being treated as a local time vs it being treated as UTC.
Just make it unambiguous by specifying the time zone. Change
var unReadableDate = "2016-01-25T00:46:00";
to
var unReadableDate = "2016-01-25T00:46:00Z";

Javascript time keeper fails to update correctly

I constructed a small clock out of Javascript code, and it fails to update correctly. It display's the time fine, but you have to refresh the page in order to get the clock to update correctly. Is there a way I can have my code update automatically without having to update the page every time?
Picture:
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
</script>
First of all, you could wrap your code in a function, say, currentTime(), changing the document.write call to a return statement, so you have a function currentTime() that returns the updated string. Then save somewhere a handle to an HTML element where you want to show the updated time, like el = document.getElementById('time'), and then use an interval like so
setInterval(function () {
el.innerHTML = currentTime();
}, 5000);
function UpdateClock(){
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10)
minutes = "0" + minutes
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
//document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
document.getElementById('myClock').innerHTML = "<b>" + hours + ":" + minutes + " " + suffix + "</b>";
}
setInterval(function(){ UpdateClock(); }, 6000);
HTML:
<div id="myClock"></div>

Categories

Resources