Javascript - Date difference is incorrect - javascript

I need to get the difference in seconds between two dates and times.
I have this script:
var date1 = new Date(2013,10,02,12,00,00);
var date2 = new Date(2013,10,02,12,01,00);
var diff = date2 - date1;
diff = diff / 1000;
document.write(diff);
Which returns the value of 60, 60 seconds difference, good.
However, when I cross over a month with 30 days, it doesn't calculate correctly.
var date1 = new Date(2013,9,30,12,00,00);
var date2 = new Date(2013,10,02,12,00,00);
var diff = date2 - date1;
diff = diff / 1000;
document.write(diff);
The result returned is 259200, which is 3 days. The difference between September 30 and October 2 is only 2 days, 172800, because there are only 30 days in the month. Why does Javascript seem to think there are 31 days in September?

The month numbers start with 0, not 1. So 9 is October and 10 is November.

Related

How to correctly calculate difference in days between 2 dates with DST change?

I have a task to get days difference between 2 dates. My solution is like here https://stackoverflow.com/a/543152/3917754 just I use Math.ceil instead of Math.round - cause 1 day and something is more than 1 day.
It was fine until I got dates between DST change. For example:
In my timezone DST change was on 30 Oct.
So when I'm trying to find days diff between dates 20 Oct and 10 Nov in result I get 23 instead of 22.
There are solution how to identify DST date but is it good solution to add/substract 1 day if date is/isn't dst?
function datediff(toDate, fromDate) {
const millisecondsPerDay = 1000 * 60 * 60 * 24; // milliseconds in day
fromDate.setHours(0, 0, 0, 0); // Start just after midnight
toDate.setHours(23, 59, 59, 999); // End just before midnight
const millisBetween = toDate.getTime() - fromDate.getTime();
var days = Math.ceil(millisBetween / millisecondsPerDay);
return days;
}
var startDate = new Date('2022-10-20');
var endDate = new Date('2022-11-10');
console.log('From date: ', startDate);
console.log('To date: ', endDate);
console.log(datediff(endDate, startDate));

Javascript - Find out if date is between two dates, ignoring year

I need to find out if my date is between two dates (for checking birthday whether its between +/- 10 days of current date) without taking care of year (because for birthday we don't need year).
I have tried the following but its typical match and will not ignore year. If i ll compare only date and month then overlap on month end makes problems.
(moment(new Date()).isBetween(moment(date).add(10, 'days'), moment(date).subtract(10, 'days')));
Here is the solution that i was end up with.
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = Math.abs(birthday - new Date) < 10*24*60*60*1000;
And if you are using moment then:
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = moment(new Date()).isBetween(moment(birthDate).subtract(10, 'days'), moment(birthDate).add(10, 'days'));
if(Math.abs(birthday - new Date) < 10/*d*/ * 24/*h*/ * 60/*min*/ * 60/*secs*/ * 1000/*ms*/)
alert("somewhat in the range");
You can just work with dates as if they were milliseconds. Just get the difference by subtracting them, then check if its smaller than 10 days in milliseconds.
You can use momentjs with methods subtract and add to find any date you want.
Example:
moment().add(7, 'days'); // next 7 days
moment().subtract(7, 'days'); // 7 days ago
This may be help you.
var birthDate = new Date("05/16/1993");
var day = birthDate.getDate();
var month = birthDate.getMonth();
var currentDate = new Date();
var tempDate = new Date();
var oneDay = 1000 * 60 * 60 * 24
var dayDifference = 10 // you can set here difference
tempDate = new Date(tempDate.setMonth(month,day))
var timeDiff = tempDate.getTime() - currentDate.getTime();
timeDiff = Math.round(timeDiff / oneDay)
if(-dayDifference <= timeDiff && timeDiff <=dayDifference){
alert("matched")
}
else{
alert("not matched")
}

How to calculate difference between two dates in hours? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
As I am new to javascript so I am asking this question how to find difference between two dates in hours.I am successfully calculated difference but when I give time in format of AM/PM it gives me output as NAN Please check my code I am posting below and thanks in advance:
function calculateTime() {
var d2 = new Date('2018-02-12 03:00:00 AM');
var d1 = new Date('2018-02-10 08:00:00 AM');
var seconds = (d2- d1)/1000;
var hours = seconds/3600;
console.log(hours);
}
calculateTime();
Simply subtract the date objects from one another.
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5 is short for 60*60*1000 and so dividing by 36e5 will give you hours.
Firefox will return Invalid date for the format YYYY-MM-DD HH:MM:SS AM
One option is to use year, month, day separately on new Date()
new Date(year, month [, day [, hours [, minutes [, seconds [,
milliseconds]]]]]);
Like:
function calculateTime() {
var formatDate = function(dt) {
let n = dt.split(/\D/).splice(0,6);
n[3] = dt.slice(-2) === 'PM' ? ( +n[3] + 12 ) : n[3]; //Update Hour
n[1] = n[1] - 1; //Update month
return n;
}
var d2 = new Date(...formatDate('2018-02-12 03:00:00 AM'));
var d1 = new Date(...formatDate('2018-02-10 08:00:00 AM'));
var seconds = (d2 - d1) / 1000;
var hours = seconds / 3600;
console.log(hours);
}
calculateTime();
Doc: new Date

hours difference between two years (With leap year) in javascript

How can i get the hours difference between two years (With leap year) in javascript
I have two year 2015 and 2014
var year1="2015";
var year="2016";
I want to get the total hours different between those above years by one line code(with leap year and without leap year)!.
I have tried this below code
// get hours from one year
var date = new Date;
var Hours= date.getFullYear().getHours();
// get hours between two years
var Hours= (date.getFullYear()-dat2.getFullYear()).getHours()
But It's something wrong for me.
You could use a function similar to this:
function getHoursBetweenYears(startYear, endYear) {
var startDate = new Date(startYear, 0, 1),
endDate = new Date(endYear, 0 ,1);
return (+endDate - +startDate) / 3600000;
}
Usage like this:
getHoursBetweenYears(2012, 2013) // 8784
Date object is your saver.
Get time differance. then multiply with min, s, ms.
Gives you time diff total hour between years.
var year=2015,
year1=2016,
timeDiff =(new Date("01/01/"+year1)-new Date("01/01/"+year))/(1000*60*60);
The leap year should be specified by year and also month. So
March d + 59 Add 1 if leap year
….up to
December d + 334 Add 1 if leap year
You can try something like this.
hours = ((new Date()).setFullYear( 2016 ) - (new Date()).setFullYear( 2015 ))/(1000*3600);
View demo jsFiddle
var start = new Date(2015, 0, 0);
var end = new Date(2016, 0, 0);
var diff = end - start;
var oneDay = 1000 * 60 * 60;
var day = Math.floor(diff / oneDay);
alert("Hours: " + day);
Answer
Hours: 8760
Calculate the diffference in milliseconds from two dates (including the first day of the start year and the last day of the end year) and divide the result by 3600000 (1000 * 60 * 60 = milliseconds in one hour):
// difference in hours for two whole years (2015-2016)
var hourdiff = (new Date('2017/01/01') - new Date('2014/12/31'))/(1000*60*60);
You can create a Date extension to calculate hours in a certain year:
Date.prototype.hoursInYear = function() {
return ( (new Date(this.getFullYear()+1, 0, 1)) -
(new Date(this.getFullYear()-1, 11, 31)) ) / 3600000; }
// usage
new Date(1997, 0, 1).hoursInYear(); // => 8784
new Date(2008, 0, 1).hoursInYear(); // => 8808 (leap year)
Or even (the number of hours in a (leap)year is constant)
Date.prototype.hoursInYear = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1
? 8808 : 8784;
}
And finally, using the Date extension, this could be a method to calculate the number of hours in [n years] starting with [startyear]:
function calcHours(startyear, numyears) {
return isNaN(new Date(startyear, 0, 1))
? null // invalid year value
: Array.apply(null, {0: startyear, length: numyears})
.map(function(v, i) {return v == this ? v : this + 1;}, startyear)
.reduce( function(a, b) {
return a + new Date(b, 0, 1)
.hoursInYear();}, 0);
}
// usage
calcHours(2000, 2); //=> 17592 (2000 is leap year)
calcHours(2001, 2); //=> 17568
Get the seconds of both years. setFullYear gives you the unix timestamp in millis. Divide by 1000 and you have seconds. Get the difference between the two years and divide this through 3600 (seconds per hour). Then you have your difference in hours.
function getDiffHours (year1, year2) {
var d1 = new Date().setFullYear(year1) / 1000;
var d2 = new Date().setFullYear(year2) / 1000;
var diff = Math.abs(d2 - d1);
return Math.floor(diff / 3600);
}

Date difference larger than intended

I am learning to use Date object in Javascript. Tried to calculate difference between now and some set date, but it returns a much larger value than inteded. The codepen is here, I can't seem to figure what I did wrong... Help?
var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
var now = new Date(); //Now, whenever this code runs
var diff = Math.round((setdate.getTime() - now.getTime())/1000); //Difference in seconds
function NiceTimer(delta) { //Decompose the difference in seconds into date units.
this.days = Math.floor(delta/ 86400);
delta -= this.days*86400; //Subtract the value once it has been "extracted".
this.hours = Math.floor(delta/ 3600);
delta -= this.hours*3600;
this.minutes = Math.floor(delta/ 60);
delta -= this.minutes*60;
this.seconds = delta;
this.printString = function() {
return "The event starts in "+this.days+" days, "+this.hours+" hours, "+this.minutes+" minutes and "+this.seconds+" seconds"; //Output a readable countdown string
}
}
var timer = new NiceTimer(diff);
var el = document.getElementById("timer");
el.innerHTML = timer.printString();
var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
Change the four to a three, months start at index zero.
var setdate = new Date(2014, 3, 27, 14,30);
Date # MDN:
month
Integer value representing the month, beginning with 0 for January to 11 for December.

Categories

Resources