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.
Related
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
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.
This question already has answers here:
Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time
(4 answers)
Closed 6 years ago.
I'm working on a project where I need to get the hours and minutes alone without the semicolon (:) separating them, and represent them in a variable, myTime, as a 4-digit number. Here is my code:
var now = new Date();
var time = now.toString().substr(16,5)
Use the .getHours() and .getMinutes() methods of Date objects to get these numbers. To get a 4-digit number representation (as a zero-padded string), concatenate and zero-pad as necessary with ('0000' + (hours * 100 + minutes)).slice(-4)as demonstrated below:
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var myTime = ('0000' + (hours * 100 + minutes)).slice(-4);
//note that myTime is a zero-padded string of length 4
console.log(now.toString(), hours, minutes, myTime);
To get Hours or Minutes from a datetime use the associated functions myDate.getHours() or myDate.getMinutes()
Edit: you probably don't want military time so adding 12 hour conversion...
var mt = getHoursMinutesSeconds(new Date());
alert(mt);
function getHoursMinutesSeconds(date) {
var h = date.getHours();
h = ((h + 11) % 12 + 1);
var m = date.getMinutes();
var myTime = addZero(h) + addZero(m);
return myTime;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
I've been working on this script to get the difference between 2 dates. But the hours will mess up the script (http://jsfiddle.net/HuGvd/).
When the script enters a new month new the same day the script stops working correctly. I've also tried adding minutes to this script with no luck really need help with this one guys.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var diffInHours = (d1H + 24 * d1D + 30) - (d2H + 24 * d2D + 30);
if (diffInHours < 24) return diffInHours + " hour";
var diffInDays = (d1D + 30 * d1M + 12) - (d2D + 30 * d2M + 12);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays >= 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}
Date/time functionality is extremely complex with more edge cases than you can possibly cover... don't roll your own solution, use built-in functionality. You can find the number of milliseconds between two dates in javascript like this:
var now = new Date();
var then = new Date(timestamp);
var diffMS = now - then;
From there, it's not too difficult to convert to whatever unit your want based on how you want to display it.
http://jsfiddle.net/AMDXq/
As a side note, this is a fairly common problem. I haven't looked, but I'm sure there's a plugin or library out there for this.
Here is a solution for finding the difference between two dates. The strategy is to convert strings to date objects, then calculate the difference and return an array of values for years, months, days, etc.
I've added a parameter for "precise" so that by default it returns a value in whole days (e.g. 2013-08-13T23:59:59Z to 2013-08-14T00:00:01Z is one day) or precise (where the above difference is 2 seconds).
// Expects start date to be before end date
// Default is to deal in whole days. For precise differences
// (hours, minutes and seconds), set precise to true
function dateDifference(start, end, precise) {
var timeDiff, years, months, days, hours, minutes, seconds;
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
console.log(s, e);
// If not precise, set h,m,s to zero
if (!precise) {
s.setUTCHours(0,0,0,0);
e.setUTCHours(0,0,0,0);
console.log(s, e);
}
// Get estimate of year difference
years = e.getUTCFullYear() - s.getUTCFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getUTCFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getUTCFullYear() + years);
}
// Get estimate of months
months = e.getUTCMonth() - s.getUTCMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setUTCMonth(s.getUTCMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setUTCFullYear(s.getUTCFullYear() + years);
s.setUTCMonth(s.getUTCMonth() + months);
}
// Get remaining time difference
timeDiff = e - s;
days = timeDiff / 8.64e7 | 0;
hours = (timeDiff % 8.64e7) / 3.6e6 | 0;
minutes = (timeDiff % 3.6e6) / 6e4 | 0;
seconds = ((timeDiff % 6e4) / 1e3).toFixed(3);
console.log(years, months, days, hours, minutes, seconds);
return [years, months, days, hours, minutes, seconds];
}
// Simple caluculation of days between two ES5 date objects
function daysDifference(start,end) {
return ((end - start) / 8.64e7).toFixed(2);
}
// Expects input in ISO8601 format: yyyy-mm-ddThh:mm:ss.sssZ
function dateFromString(s) {
s = s.split(/\D/);
s[6] = s[6]? ('0.'+ s[6]) * 1000 : 0;
return new Date(Date.UTC(s[0],--s[1],s[2],s[3],s[4],s[5],s[6]));
}
function getDateDiff(start, end, precise) {
var d = dateDifference(dateFromString(start), dateFromString(end), precise);
return d[0] + ' years, ' + d[1] + ' months, ' + d[2] + ' days' +
(precise? ', ' + d[3] + ' hours, ' + d[4] + ' minutes and ' + d[5] + ' seconds' : '') ;
}
function getDaysDiff(start, end) {
var d = daysDifference(dateFromString(start), dateFromString(end));
return d + ' days';
}
</script>
<!-- Some HTML to show how to use it -->
<form onsubmit="this.doCalc.onclick(); return false;">
<label for="startDate">Start date (yyyy-mm-dd)<input name="startDate" id="startDate"
value="2012-08-09T22:15:03.22" size="25"></label>
<br>
<label for="endDate">End date (yyyy-mm-dd)<input name="endDate" id="endDate"
value="2013-08-13T12:10:03.22" size="25"></label>
<br>
<label for="dateDifference">Date difference: <input name="dateDifference" readonly size="100"></label>
<br>
<label for="daysDifference">Days difference: <input name="daysDifference" readonly size="100"></label>
<br>
<label for="precise"><input type="checkbox" value="precise" name="precise" id="precise">Precise?</label>
<br>
<input type="button" value="Calculate…" name="doCalc" onclick="
this.form.dateDifference.value = getDateDiff(this.form.startDate.value, this.form.endDate.value,
this.form.precise.checked);
this.form.daysDifference.value = getDaysDiff(this.form.startDate.value, this.form.endDate.value);
">
<input type="reset">
</form>
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).