I need to get the system time once, then store it on localStorage, then compare this stored value with a further system date and then perform an action if the future date is equal or greater than the one which is stored. I have tried but I am stucked in making the function which gets the system time the first time to run only once so I can get a future date to compare.
This is my code
console.log(formatTime());
function formatTime() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
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;
return (strTime = date.getDay() + "/" + date.getMonth() + "/" + date.getFullYear() + " " + hours + ":" + minutes + ":" + seconds + " " + ampm);
}
document.getElementById("currentdt").innerHTML = strTime;
var strTime1 = formatTime();
var timeString = JSON.stringify(strTime1);
localStorage.setItem("strTime1", timeString);
var timeStringFromLocalStorage = localStorage.getItem("strTime1");
var timeFromLocalStorage = JSON.parse(timeStringFromLocalStorage);
document.getElementById("time").innerHTML = strTime1;
console.log(timeStringFromLocalStorage);
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA, "strTime1");
var momentB = moment(dateTimeB, "strTime");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("strTime1", "strTime"));
The function below will check if there has been a value set in localStorage. If there is no value set, it will set its first and stop the function.
If there is a value, then it will be turned into a moment instance and compared with the current date. If a difference in days is equal or larger to than specified it will redirect the page.
function redirectWhenOlderThan(days, url) {
const storedValue = localStorage.getItem('first-visit');
const now = moment();
/**
* If nothing is stored yet, then storedValue will be null.
* Here you will set the first localStorage item for the first time.
* Instead of a full date, store the timestamp.
* Then stop the function.
*/
if (storedValue === null) {
localStorage.setItem('first-visit', now.valueOf().toString());
return;
}
/**
* If there is a stored value then it will be a timestamp as a string.
* First parse it into a number before putting it into moment.
* Then check the difference in days between the dates.
*/
const then = moment(Number(storedValue));
const difference = now.diff(then, 'days');
/**
* If the difference is higher or equal to the given days, redirect.
*/
if (difference >= days) {
location.href = url;
}
}
Call the function with amount of days that should have passed since the first visit and the URL to redirect to.
redirectWhenOlderThan(15, 'https://example.com');
I hope this is what you meant.
Sidenote: dive into moment.js if you have the time. It has a lot of features that could spare you some time, like your formatTime() function, it can be written in a single line with moment.
moment().format('DD/MM/YYYY h:mm:ss A');
Now the final code goes like this
function formatTime() {
var date = new Date();
return strTime = date.getDay() + '/' + date.getMonth()+'/'+date.getFullYear();
}
document.getElementById("currentdt").innerHTML = strTime;
function redirectWhenOlderThan(days, url) {
const storedValue = localStorage.getItem('first-visit');
const now = moment();
if (storedValue === null) {
localStorage.setItem('first-visit', now.valueOf().toString());
return;
}
const then = moment(Number(storedValue));
const difference = now.diff(then, 'days');
if (difference >= days) {
location.href = url;
}
else {
window.location.href= 'app/phr.html';
}
}
setTimeout(function () {
redirectWhenOlderThan(1, 'app/licences.html');
}, 3000);
Related
In my application, I need to create live clock according to different timezones which are stored into database.
I have almost succeeded it.
But now I'm facing negative time in clock, and I'm out of ideas to figure out a solution.
I'm getting UTC time with the help of new Date() and calculating time with provided timezone from database.
Case 1: 0:31 (UTC time) + 5:30 (timezone) = '06:01'
Case 2: 06:31 (UTC time) - 6:30 (timezone) = '00:01'
Case 3: 5:0 (UTC time) - 7:0 (timezone) = '-02:00'
Case 1 and 2 is working properly but I'm getting negative value in 3rd case which is wrong.
I have tried to add comments in code to have better understanding of what I'm doing here. I hope it helps.
Any help will be highly appreciated.
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You should just be "looping back" to 23:59 when you go negative. You can just add something to check if it goes negative then just re-add the missing time:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
But ideally you really don't want to be handling these kinds of Timezone issues as other libraries are already handling it, i.e. moment.js
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You want to recover/display the time for a given timezone offset? Unless you like doing this for a hobby, stay away from string methods and use the date functions, no?
var offsetMS = -5.5 * 3600000
var myDate = new Date()
var dateWithOffset = new Date( myDate.getTime() + offsetMS )
var formatted = dateWithOffset.toLocaleString("en-GB",{timeZone:"UTC",hour:"numeric",minute:"numeric"})
console.log(formatted)
Even manipulating timezone offset directly is to be avoided. If you can, use toLocaleString with a real timezone name, then issues like daylight saving will be handled for you. Modern browsers support all iana timezones, so let them do the work.
Add 24 to your FT value and take division remain of 24:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME + 24;
FT = FT % 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
Working sample: https://codepen.io/anon/pen/VqQqoo
If you do not want to use a library like moment.js that comes with time zone handling and simply need to add/subtract hours from a given date, how about converting them to a common time unit and operating on that?
const timezoneString = '-:12:30';
const parts = timezoneString.split(':');
const timezone = (parts[0] === '-' ? -1 : 1) * (parseInt(parts[1]) + (parseInt(parts[2]) / 60.0));
const timeZoneMillis = timezone * 3600 * 1000;
const now = new Date();
const inZone = new Date(now.getTime() + timeZoneMillis);
console.log(now, inZone);
Something like this would convert them to a millisecond timestamp and subtract that many hours and convert it back to a date.
I have this javascript code which should show the time. It works. I wan't to be able to add extra time though. Lets say that I want to add 1 hour.
<script type="text/javascript">
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
// This function gets the current time and injects it into the DOM
function updateClock() {
// Gets the current time
var now = new Date();
// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// Format hours, minutes and seconds
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');
// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds;
}
function start(){
setInterval('updateClock()', 200);
}
</script>
The first function calculates the milisecons that I want to add, and the second function is the "live clock". How do I implement the first function into the second one, so I get the working result?
for adding hours, use setHours :
// Gets the current time
var now = new Date();
console.log("actual time:", now);
now.setHours(now.getHours() + 1)
console.log("actual time + 1 hour:", now);
For references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
Check out this fiddle.
The constructor Date(milliseconds) of class Date can be used here.
Here is the snippet.
var now = new Date();
alert(now);
var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000);
var later = new Date(milliseconds);
alert(later);
Check out this
fiddle here
var todayDate = new Date();
alert("After adding ONE hour : "+new Date(todayDate.setHours(todayDate.getHours()+1)) );
javascript date API is near to be completed, the existing methods of it can be use to add another functionality for this API, some says it is tedious but its not.
in order to add a method in a date we will access the prototype of this API,
like this.
Date.prototype.addTime = function(str){
function parse(str){
let arr = (typeof str == 'number')?[str]:str.split(":").map(t=>t.trim());
arr[0] = arr[0] || 0;
arr[1] = arr[1] || 0;
arr[2] = arr[2] || 0;
return arr
}
function arrToMill(arr){
let [h,m,s] = arr;
return (h*60*60*1000) + (m*60*1000) + (s*1000);
}
let date = new Date(this.getTime());
let parsed = parse(str);
date.setTime(date.getTime() + arrToMill(parsed));
return date;
}
getting it rockin.
this function is immutable
let date = new Date();
date.addTime(1);
date.addTime("01:00");`
I need to make countdown timer for every day to 21:00. Counting till live stream.
If time is less then 21:00 display the time left and if time is from 21:00-22:00
I would like to display 'streaming right now'. After 22:00 start counting till tomorrow at 21:00.
Any suggestins how to do this?
Here is what I tried so far but it doesn't work well and also if client change the time on his computer the counter will change. I need to fix that on server side so for everyone it will show the same time.
<script type="text/javascript">
$(document).ready(function(){
var curT, tarT, difT;
curT = new Date().getTime()/1000;
tarT = new Date('<?php echo (new DateTime('May 05, 2014'))->add(new DateInterval("P1D"))->format('M d, Y');?>, 21:00:00').getTime()/1000;
init();
function init(){
var d,h,m,s;
difT = tarT - curT;
function updateT(){
s = difT;
d = Math.floor(s/86400);
s -= d * 86400;
h = Math.floor(s/3600);
s -= h * 3600;
m = Math.floor(s/60);
s -= m * 60;
s = Math.floor(s);
}
function tick(){
clearTimeout(timer);
updateT();
displayT();
if(difT>0){
difT--;
timer = setTimeout(tick,1*1000);
} else {
$('.timeleft').html('Aukcija u toku...');
}
}
function displayT(){
var out;
out = h+":"+m+":"+s;
$('.timeleft').html(out);
}
var timer = setTimeout(tick,1*1000);
}
});
</script>
Since you need a combination of both scripts from above, I combined them for you: http://jsfiddle.net/69TAf/
Reads out the real time from GMT Server
Clients timezone doesn't matter
GMT Server is only pinged once at beginning (for better performance)
Added leading zeros so it looks better
Credits to edcs and Miskone!
var date;
var display = document.getElementById('time');
$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});
setInterval(function() {
date = new Date(date.getTime() + 1000);
var currenthours = date.getHours();
var hours;
var minutes;
var seconds;
if (currenthours != 21){
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
display.innerHTML = hours + ':' + minutes + ':' +seconds;
} else {
display.innerHTML = 'LIVE NOW';
}
}, 1000);
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
And html:
<div id='time'></div>
If you don't want to ping an external server for getting the time, you can use this fiddle (not working on jsfiddle, since contains php):
http://jsfiddle.net/qQ6V3/ - I think it's even better this way.
If you need everyone to be counting down from the same time, then you'll need to grab it from a centralised time server. This code does exactly that:
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
// This is where you do whatever you want with the time:
alert(time);
});
Source
If you use getTime() instead of grabbing the local time from the client then everyone will be in sync.
you can do something like this :
<div id='time'></div>
and the script :
var display = document.getElementById('time');
setInterval(function(){
var date = new Date();
var currenthours = date.getHours();
var hours;
var minutes;
var secondes;
if (currenthours != 21){
if (currenthours < 21)
hours = 20 - currenthours;
else hours = 21 + (24 - currenthours);
minutes = 60 - date.getMinutes();
secondes = 60 - date.getSeconds();
display.innerHTML = hours + ':' + minutes + ':' +secondes;
}
else display.innerHTML = 'LIVE NOW';
},1000);
fiddle: http://jsfiddle.net/KbM8D/
Lots of answers, one more won't hurt. :-)
I think you are best to pass the start and end of streaming to the client as a UNIX UTC time values in seconds. Then the client can turn that into a local date and count down to that. Using a network time server sounds good, but it means that everyone must use the same time server and you are reliant on the server being available.
if you're going to pass a time at all, it might as well be the start and end according to your server. You can even pass the current time from the server and calculate a time offset to apply at the client. Anyhow, the code…
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'streaming right now';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(21,0,0,0);
var myEnd = new Date()
myEnd.setHours(22,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<div id="foo"></div>
I am using the following script below, and what I am trying to do is to set a custom time to the script and for it to auto update without the need to re-set the time each time. (I only want to set the time once and want my script to keep track of the time and display it)
When I run the script it displays: NaN:NaN:NaN AM
My Code is as follows:
<div id="js_clock"> display clock here </div>
<script language="javascript">
function js_clock(clock_time)
{
var clock_hours = clock_time.getHours();
var clock_minutes = clock_time.getMinutes();
var clock_seconds = clock_time.getSeconds();
var clock_suffix = "AM";
if (clock_hours > 11){
clock_suffix = "PM";
clock_hours = clock_hours - 12;
}
if (clock_hours == 0){
clock_hours = 12;
}
if (clock_hours < 10){
clock_hours = "0" + clock_hours;
}
if (clock_minutes < 10){
clock_minutes = "0" + clock_minutes;
}
if (clock_seconds < 10){
clock_seconds = "0" + clock_seconds;
}
var clock_div = document.getElementById('js_clock');
clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
setTimeout("js_clock()", 1000);
}
var serverTime = new Date("09:20:50");
js_clock(serverTime);
</script>
You have a problem creating the date, new Date("09:20:50"); returns Invalid Date.
if you want to set hours minutes and seconds use
new Date(year, month, day [, hour, minute, second, millisecond ])
or take a look here.
Also you forgot to pass a date to the setTimeout, try:
setTimeout(function() {
js_clock(new Date(/*pass hours minutes and seconds here*/))
}, 1000);
I think you've forgotten passing an argument to js_clock(). Maybe you shoud do:
setTimeout(
function() {
//Call the function again updating seconds by 1
js_clock(
new Date(
clock_time.getFullYear(),
clock_time.getMonth(),
clock_time.getDate(),
clock_time.getHours(),
clock_time.getMinutes(),
clock_time.getSeconds() + 1
)
);
},
1000
);
EDIT:
I missed the point this can be done with a single function call:
setTimeout(
function() {
js_clock(new Date(+clock_time + 1000));
},
1000
);
The +clock_time statement converts the Date object to milliseconds from the UNIX Epoch, so updating the time is as simple as summing 1000 milliseconds.
Thanks to user RobG ;-)
Your code has some serious flaws, such as the following.
setTimeout doesn't run at exactly the interval set, but as soon as it can afterward so this clock will slowly drift, sometimes by a lot.
Passing a string to Date and expecting it to be correctly parsed is problematic. In ECMA-262 ed 3 it was entirely implementation dependent, in ES5 the string is required to be a custom version of the ISO8601 long format (but note that not all browsers in use support ES5).
Lastly, if the client is busy, the function may not run for several seconds so the clock needs to be based on the client clock, then ajusted for the time difference.
The following function does all the above.
<script type="text/javascript">
var customClock = (function() {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10? '0' : '') + n;
}
function formatTime(d) {
return addZ(d.getHours()) + ':' +
addZ(d.getMinutes()) + ':' +
addZ(d.getSeconds());
}
return function (s) {
var now = new Date();
var then;
// Set lag to just after next full second
var lag = 1015 - now.getMilliseconds();
// Get the time difference if first run
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function() {
customClock('09:20:50');
}
</script>
<div id="clock"></div>
WAIT! just realised, this is still not showing the correct time. The error is gone, but the time isn't what you are looking for.
window.js_clock = function js_clock(clock_time) {
var clock_hours = clock_time.getHours();
var clock_minutes = clock_time.getMinutes();
var clock_seconds = clock_time.getSeconds();
var clock_suffix = "AM";
if (clock_hours > 11) {
clock_suffix = "PM";
clock_hours = clock_hours - 12;
}
if (clock_hours === 0) {
clock_hours = 12;
}
if (clock_hours < 10) {
clock_hours = "0" + clock_hours;
}
if (clock_minutes < 10) {
clock_minutes = "0" + clock_minutes;
}
if (clock_seconds < 10) {
clock_seconds = "0" + clock_seconds;
}
var clock_div = document.getElementById('js_clock');
clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
setTimeout("js_clock(new Date())", 1000);
}
var serverTime = new Date("09:20:50");
window.js_clock(serverTime);
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).