I have 2 dates in ISO format like so:
startDate: "2018-09-14T00:20:12.200Z"
endDate: "2018-09-16T00:18:00.000Z"
What I'm trying to do is calculate the difference between those 2 days. So with the given dates it would be 1 Day, 21 Hours, 47 Minutes and 40 Seconds (pardon me if the subtraction is not correct).
Tried to do using the following:
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
return Math.abs(end - start).toString();
However this doesn't seem to work.
Any clues?
The following works. Things to note:
getTime() is not needed as the new Date() constructor returns the time in milliseconds.
The date should always be in RFC2822 or ISO formats, else it becomes useless across various browsers, even while using moment.js.
If you can use moment.js, Get time difference using moment.
Refer this to know why only the standardized formats need to be used.
var unitmapping = {"days":24*60*60*1000,
"hours":60*60*1000,
"minutes":60*1000,
"seconds":1000};
function floor(value)
{
return Math.floor(value)
}
function getHumanizedDiff(diff)
{
return floor(diff/unitmapping.days)+" days "+
floor((diff%unitmapping.days)/unitmapping.hours)+" hours "+
floor((diff%unitmapping.hours)/unitmapping.minutes)+" minutes "+
floor((diff%unitmapping.minutes)/unitmapping.seconds)+" seconds "+
floor((diff%unitmapping.seconds))+" milliseconds";
}
console.log(getHumanizedDiff(new Date("2018-09-16T00:18:00.000Z") - new Date("2018-09-14T00:20:12.200Z")));
console.log(getHumanizedDiff(new Date("2018-09-16T00:18:00.000Z") - new Date("2018-09-04T00:20:02.630Z")));
console.log(getHumanizedDiff(new Date("2018-09-17T00:16:04.000Z") - new Date("2018-09-14T00:20:12.240Z")));
var startDate = "2018-09-14T00:20:12.200Z"
var endDate = "2018-09-16T00:18:00.000Z"
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const milliseconds = Math.abs(end - start).toString()
const seconds = parseInt(milliseconds / 1000);
const minutes = parseInt(seconds / 60);
const hours = parseInt(minutes / 60);
const days = parseInt(hours / 24);
const time = days + ":" + hours % 24 + ":" + minutes % 60 + ":" + seconds % 60;
console.log(time)
yBrodsky's suggestion to use moment.js is probably the best idea, but if you're curious how to do the math here, it would go something like this:
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
let seconds = Math.round(Math.abs(end - start) / 1000); // We'll round away millisecond differences.
const days = Math.floor(seconds / 86400);
seconds -= days * 86400;
const hours = Math.floor(seconds / 3600);
seconds -= hours * 3600;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
This leaves you with hours, minutes, and seconds as numbers that you can format into a string result however you like.
Happy new year everyone,,
I'm using this function to get the time left between today and giving date (Hours:Minutes) and it works fine...
function PrayerTimeLeft(prayerTime){
var today = new Date();
var prayerTimeDate = new Date();
prayerTimeDate.setHours(prayerTime.substring(0,2));
prayerTimeDate.setMinutes(prayerTime.substring(3,5));
var diffMs = (prayerTimeDate - today);
var diffHrs = Math.round((diffMs % 86400000) / 3600000);
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000);
return {
getDiffMin:function(){
return diffMins;
},
getDiffHrs:function(){
return diffHrs;
}
};
}
I can use it like this:
var test = new PrayerTimeLeft("14:00"); // and today was 12:00 in 24 format
console.log(test.getDiffHrs()); //It will show 2 hours
I'm here trying to get how many left for a coming Prayer time, there are five Prayers: First: 5:00
Second: 11:42
Third: 14:26
Fourth: 16:50
Fifth: 18:07
My problem is if the current time (let's say it will 23:00) is between fifth and first one, here we are talking about tomorrow time which is between (5:00 & 18:07)
I can't realize this reverse things?
I have 3 suggestions:
Return only references to functions. Your pattern becomes messy with, let's say, 4+ methods.
If you are sure you'll get a string HH:MM, why don't you simply split it?
Avoid setting secondary variables just like you did. If you already have primary values (today and prayerTime) and you are able to derive various new measures (like hours, min, secs etc. left) leave your object as stateless as you can.
Some other patterns would suggest declaring functions AFTER the return statement (instead of declaring vars and anonymous functions)
function PrayerTimeLeft(prayerTime) {
var today = new Date();
var prayerTimeDate = new Date();
var setPrayerTime = function() {
var prayerHours = prayerTime.split(':')[0];
var prayerMin = prayerTime.split(':')[1];
if (today.getHours() >= prayerHours) {
prayerTimeDate.setDate(today.getDate() + 1);
}
prayerTimeDate.setHours(prayerHours);
prayerTimeDate.setMinutes(prayerMin);
};
var getDiffMin = function() {
return (prayerTimeDate - today) / 1000 / 60;
};
var getDiffHrs = function() {
return Math.floor((prayerTimeDate - today) / 1000 / 60 / 60);
};
setPrayerTime();
return {
getDiffMin: getDiffMin,
getDiffHrs: getDiffHrs
};
}
And testing:
var test = new PrayerTimeLeft("00:00"); // and today was 12:00 in 24 format
console.log(test.getDiffMin()); //It will show total minutes left
console.log(test.getDiffHrs()); //It will show total hours left (without minutes) 14:59 left will be shown as 14 hours left (15 hours would be more inaccurate).
EDIT: If you want to return HH:MM, here is a snippet with extra function.
function PrayerTimeLeft(prayerTime) {
var today = new Date();
var prayerTimeDate = new Date();
var setPrayerTime = function() {
var prayerHours = prayerTime.split(':')[0];
var prayerMin = prayerTime.split(':')[1];
if (today.getHours() >= prayerHours) {
prayerTimeDate.setDate(today.getDate() + 1);
}
prayerTimeDate.setHours(prayerHours);
prayerTimeDate.setMinutes(prayerMin);
};
var getDiffMin = function() {
return (prayerTimeDate - today) / 1000 / 60;
};
var getDiffHrs = function() {
return Math.floor((prayerTimeDate - today) / 1000 / 60 / 60);
};
var getDiffString = function() {
return Math.floor(getDiffMin() / 60) + ':' + getDiffMin() % 60;
}
setPrayerTime();
return {
getDiffMin: getDiffMin,
getDiffHrs: getDiffHrs,
getDiffString: getDiffString
};
}
I have a function that will calculate time between two date / time but I am having a small issue with the return.
Here is the way I collect the information.
Start Date
Start Time
Ending Date
Ending Time
Hours
And here is the function that calculates the dates and times:
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var sec = date2.getTime() - date1.getTime();
if (isNaN(sec)) {
alert("Input data is incorrect!");
return;
}
if (sec < 0) {
alert("The second date ocurred earlier than the first one!");
return;
}
var second = 1000,
minute = 60 * second,
hour = 60 * minute,
day = 24 * hour;
var hours = Math.floor(sec / hour);
sec -= hours * hour;
var minutes = Math.floor(sec / minute);
sec -= minutes * minute;
var seconds = Math.floor(sec / second);
var min = Math.floor((minutes * 100) / 60);
document.getElementById("result").value = hours + '.' + min;
}
If I put in todays date for both date fields and then 14:30 in the first time field and 15:35 in the second time field the result is shown as 1.8 and it should be 1.08
I didn't write this function but I am wondering if someone could tell me how to make that change?
Thank you.
If I understand correctly, the only issue you are having is that the minutes are not padded by zeroes. If this is the case, you can pad the value of min with zeroes using this little trick:
("00" + min).slice(-2)
I can't see why 15:35 - 14:30 = 1.08 is useful?
Try this instead:
function timediff( date1, date2 ) {
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms/1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var hours = Math.floor(difference_ms % 24);
var days = Math.floor(difference_ms/24);
return [days,hours,minutes,seconds];
}
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var diff = timediff(date1, date2);
document.getElementById("result").value = diff[1] + ':' + diff[2];
}
Verify if number of minutes is less than 10 and if it is then append an additional zero in front. Follow similar approach for seconds.
I've got this js:
<script>
$('#appt_start').val(parent.location.hash);
$('#appt_end').val(parent.location.hash);
</script>
which gets the hash value from the url something.com/diary.php#0800 for example.
The value is then used to autofill the start and end times in an appointment form.
I need the second time (#appt_end) to be incremented by 15 minutes? Any ideas how I do this, my js is rubbish...
Thanks!
EDIT
Here's the working code I'm now using:
// add the time into the form
var hashraw = parent.location.hash;
var minIncrement = 15; // how many minutes to increase
hash = hashraw.replace("#", ""); // remove the hash
// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)
// add the new minutes, and enforce it to fit 60 min hours
var newMins = (mins + minIncrement )%60;
// check if the added mins changed thehour
var newHours = Math.floor( (mins + minIncrement ) / 60 );
// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);
$('#appt_start').val(hash);
$('#appt_end').val( endTime );
You need to split the time in hours / mins and then apply time logic to it to increase it..
var hash = parent.location.hash.replace('#','');
var minIncrement = 15; // how many minutes to increase
// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)
// add the new minutes, and enforce it to fit 60 min hours
var newMins = (mins + minIncrement )%60;
// check if the added mins changed thehour
var newHours = Math.floor( (mins + minIncrement ) / 60 );
// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);
$('#appt_start').val( hash );
$('#appt_end').val( endTime );
Check it out at http://www.jsfiddle.net/gaby/cnnBc/
try this:
<script>
$(function() {
$('#appt_start').val(parent.location.hash);
var end = parent.location.hash;
end = end.replace("#", "");
end = (end * 1) + 15;
if (end < 1000) {end = '0' + end};
$('#appt_end').val(end);
});
</script>
Would it be possible like this?
Working Demo
var hash="08:00";
$('#appt_start').val(hash);
var d = new Date("October 13, 1975 "+hash)
d.setMinutes(d.getMinutes()+15);
$('#appt_end').val(d.getHours()+":"+d.getMinutes());
You use a fictitious date so to sum the minutes.
If the hash has not the ":", you can do a substring to insert the ":".
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).