Changing time zones for JS clock display - javascript

I am using this code to display the current time on a site I'm building.
https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
Could someone tell me what code to add in order change the time to a different time zone? I'd also love the time to display 12 hour increments rather than 24.
Any help would be appreciated.

You can change the time zone by converting the time to UTC and adding the needed number of hours
var utc = today.getTime() + (today.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * -2));
As for converting to 12 hour format
var h = newDate.getHours() % 12;
function startTime(id, offset) {
var today = new Date();
var utc = today.getTime() + (today.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * -2));
var h = newDate.getHours() % 12;
var m = newDate.getMinutes();
var s = newDate.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="startTime();">
<div id="txt"></div>
</body>
</html>
edit
As mentioned by #BrockLee in a comment - as it is it will, indeed, show 12'o clock as 0. If this is not desired, you could change the line that sets the hours to, for example,
var h = (newDate.getHours() % 12 == 0) ? 12 : newDate.getHours() % 12;

In that example, you could use today.toLocaleTimeString() instead to show it in the preferred format of current user's locale.
Also, MDN's documentation on Date/Time related functionality in JavaScript will probably be much more helpful.

Related

How to add hours to string formatted as HH:MM:SS in 24 hour format

I'm trying to add hours to time in the format of 24 hours say '23:59:59'. I need to add, for example, 2.5 hours so the time should roll to the next day and be shown as '02:30:00'.
What I have tried so far works until it reaches '23:59:59'. I need to show the next day time if it exceeds '23:59:59'. Here is what I have tried so far:
var time = $('#starttime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var time2 = $('#endtime').val().split(':');
var endtimeval = new Date();
endtimeval.setHours(+time2[0]);
endtimeval.setMinutes(time2[1]);
endtimeval.setSeconds(time2[2]);
var str = d.getHours() + parseInt($('#noofhours').val()) + ":" + time2[1] + ":" + time2[2];
$('#endtime').val(str);
Using a Date Object here is possibly unnecessary, modulo arithmetic should suffice.
const pad = n => {
const s = String(n);
return s.length > 1 ? s : '0' + s;
};
const addHours = (timeVal, numHours) => {
const [hr, min, sec] = timeVal.split(':').map(Number);
const [,lefty, righty] = String(numHours).match(/(\d+)(?:(\.\d+))?/).map(Number);
const hours = (hr + lefty) % 24;
const minutes = righty === undefined ?
min :
((righty * 60 | 0) + min) % 60;
return [hours, minutes, sec].map(pad).join(':');
};
addHours('23:59:59', 2.5) // "01:29:59"
Note that since there's no dates involved it will not accurately handle e.g. daylight savings time. Also note that minutes are in this example rounded down, you could repeat the logic for seconds if desired.
Note that your approach using Date objects will give different answers for the same inputs depending on when/where the logic runs, for the same reasons.
Make a custom date adder?
const add = (time, hours) => {
let [hh, mm, ss] = time.split(':');
const seconds = hours * 60 * 60;
ss = ss * 1 + seconds;
if (ss >= 60) {
mm = mm * 1 + ss / 60;
ss = (ss % 60).toPrecision(2).padStart(2, '0');
}
if (mm >= 60) {
hh = hh * 1 + mm / 60;
mm = (mm % 60).toPrecision(2).padStart(2, '0');
}
hh = (Math.floor(hh) % 24).toString().padStart(2, '0');
return hh + ':' + mm + ':' + ss;
}
console.log(add("23:59:59", 2.5));
you may apply DRY principle and refactor the code yourself. But it will get the job done according to your requirement.
The simple trick that I did is just converted the hours entered as float/int to a minute value by multiplying to 60 and created a date, with this just added the time I already have.
Here the solution with minimal steps:
var time = $('#endtime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var addeddate = new Date();
addeddate.setMinutes(parseFloat($('#noofhours').val()) * 60);
$('#endtime').val(("0" + (addeddate.getHours())).slice(-2) + ":" + ("0" + (addeddate.getMinutes())).slice(-2) + ":" + ("0" + (addeddate.getSeconds())).slice(-2)); //The answer that I needed in endtime id value.
You can use vanilla JavaScript Date methods fairly easily here. Most of the work is parsing the time string inputs and then concatenating the time string output. For example:
const start = '23:59:59';
const add = '2.5';
const [hh, mm, ss] = start.split(':').map(x => parseInt(x));
const d = new Date(new Date().setHours(hh, mm + (add * 60), ss));
const end = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(end);
// 2:29:59

Countdown count with GMT time from server

I need to work on a countdown counter for a specific future date-time. I managed to use following counter http://www.blacktie.co/demo/counter/ and made some minor changes to it when i was almost done i noticed that this counter use local system date & when i change the system date it is reflected on the counter. How can this script be modified to so that it will take GMT date from server when it starts counter rather than local date.
So that every users irrespective of their location will see the exact date-time of even happening in India.
Fiddle example
http://jsfiddle.net/635hf1je/1/
script
(function ($) {
/**
* Set your date here (YEAR, MONTH (0 for January/11 for December), DAY, HOUR, MINUTE, SECOND)
* according to the GMT+0 Timezone
**/
var launch = new Date(2014, 11, 04, 12, 00);
/**
* The script
**/
var message = $('#message');
var days = $('#days');
var hours = $('#hours');
var minutes = $('#minutes');
var seconds = $('#seconds');
setDate();
function setDate() {
var now = new Date();
if (launch < now) {
days.html('<h1>0</H1><p>Day</p>');
hours.html('<h1>0</h1><p>Hour</p>');
minutes.html('<h1>0</h1><p>Minute</p>');
seconds.html('<h1>0</h1><p>Second</p>');
message.html('coming soon...');
} else {
var s = -now.getTimezoneOffset() * 60 + (launch.getTime() - now.getTime()) / 1000;
var d = Math.floor(s / 86400);
days.html('<h1>' + d + '</h1><p>Day' + (d > 1 ? 's' : ''), '</p>');
s -= d * 86400;
var h = Math.floor(s / 3600);
hours.html('<h1>' + h + '</h1><p>Hour' + (h > 1 ? 's' : ''), '</p>');
s -= h * 3600;
var m = Math.floor(s / 60);
minutes.html('<h1>' + m + '</h1><p>Minute' + (m > 1 ? 's' : ''), '</p>');
s = Math.floor(s - m * 60);
seconds.html('<h1>' + s + '</h1><p>Second' + (s > 1 ? 's' : ''), '</p>');
setTimeout(setDate, 1000);
message.html('coming soon...');
}
}
})(jQuery);
Are you looking for this : http://jsfiddle.net/lotusgodkk/635hf1je/2/ ?
Just convert the Javascript Date object into UTC.
var t = new Date();
var now = new Date(t.getUTCFullYear(), t.getUTCMonth(), t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds());
in setDate() function.
You can use php for getting the server time:
var now = <?php echo date("Y-m-d H:i:s");// Format it as you need it ?>

How to calculate the difference between actual time and display countdown?

I would like to display the difference between two times.
The first time is the actual time that I can display through:
window.setInterval("timefunc()",1000);
function timefunc(){
d = new Date ();
h = (d.getHours () < 10 ? '0' + d.getHours () : d.getHours ());
m = (d.getMinutes () < 10 ? '0' + d.getMinutes () : d.getMinutes ());
s = (d.getSeconds () < 10 ? '0' + d.getSeconds () : d.getSeconds ());
document.getElementById("time").innerHTML =
+ h + ':' + m + ':' + s;
}
Now I would like to extend this function. The second time is every day the same at 8pm.
Now for example it is 6:30pm. Here I would like to display the time left as a countdown. In this case something like: "Time left: 1:29:59". When the time is up there should be a reload of the page.
I`m totally new to Javascript and did not found any example somewhere.
I really would appreciate if there is someone who could help me out.
Thanks alot.
You can create a date object for 8:00 pm (20:00) today using:
var d = new Date();
d.setHours(20,0,0,0);
To find the difference between two dates in milliseconds, simply subtract one from the other:
var ms = d - new Date();
To convert to hh:mm:ss:
var hours = ms / 3.6e6 | 0;
var mins = (ms % 3.6e6) / 6e4 | 0;
var secs = (ms % 6e4) / 1e3 | 0;
To padd single digit numbers:
function pad(n) {return (n<10? '0':'') + n;}
and format the output:
pad(hours) + ':' + pad(mins) + ':' + pad(secs);
Maybe you want the count down to tick over after 8 pm. In that case, just check if the current date is after 8 pm. If it is, just add one to the date of the 8 pm date object:
var d = new Date();
d.setHours(20,0,0,0);
var now = new Date();
if (d < now) d.setDate(d.getDate() + 1);
So if now is after 8 pm (20:00), d is 8 pm tomorrow.

JavaScript code to run the Clock (date and time) four times faster

I am in need of virtual time (4 x current date and time). I have managed to display the running clock with the current date and time, but I am unable to the time four times faster than current time.
For example, if the current date is 01-01-2012 00:00:00, the virtual time should
be 01-01-2012 00:00:04
Not only the seconds alone should get multiplied; the corresponding minutes, hours, date, month and year also should get multiplied when seconds crosses 59 virtual seconds. That is, the clock should run live with incremental of four seconds for every second with my date format.
Please see my page: http://www.chemfluence.org.in/sample.html
It's now running with the current time. I want to run this four times faster.
Please see my code below.
<!DOCTYPE html>
<html>
<head>
<script>
function startTime()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// Add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
today.getDate() +
"-" +
(today.getMonth()+1)+"-" +
today.getFullYear() +
" "+h+":"+m+":"+s;
t = setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i = "0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
There is a simple formula to determine the virtual time for every given time, knowing the two timestamps and the factor:
var virtualOrigin = Date.parse("2012-01-01T00:00:04"),
realOrigin = Date.parse("2012-01-01T00:00:00"),
factor = 4;
function getVirtual(time) {
return new Date( virtualOrigin + (time - realOrigin) * factor );
}
// usage:
var now = new Date(),
toDisplay = getVirtual(now);
Demo at jsfiddle.net
determine the current time ("START") (as timestamp -- count of seconds since 1970)
when displaying the clock, display (("CURRENT" - "START") * 4) + "START" instead
You can do a setInterval for 1 second and then add 4 seconds to the current date.
(This example just logs the time to the console, but you can easily hook it up to an HTML element.)
var date = new Date();
setInterval(function(){
date = new Date(date.getTime() + 4000);
console.log(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
}, 1000);

How to add hours to a Date object?

It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).

Categories

Resources