Calculating how many days between dates, diffrent months [duplicate] - javascript

This question already has answers here:
Why does the month argument range from 0 to 11 in JavaScript's Date constructor?
(10 answers)
Closed 5 years ago.
So I'm playing around JavaScript's Date object, and I ran into something I think is a little strange.
I'm trying to figure out how many days there is between 2 given dates, and for that I use the formula below:
var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
If you take 2017-05-28 & 2017-05-30 it returns 2 days - as it should
var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
If you take 2017-05-30 & 2017-06-01 it returns 1 days - supposed to be 2 days
var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
If you take 2017-05-30 & 2017-06-01 it returns 3 days - supposed to be 2 days
var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 11, 29);
var secondDate = new Date(2017, 12, 01);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

I had used 1½ hour trying to figuring out what the problem was - and 10 sec after posting i figure it out.
Problem is, the date object takes:
Jan, as 0
Feb, as 1
...
...
Nov, as 10
Dec, as 11

Please remember that Date constructor allows also values from outside the logical range.
Example: new Date(2017, -2, 30)
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Where Date is called as a constructor with more than one argument, if
values are greater than their logical range (e.g. 13 is provided as
the month value or 70 for the minute value), the adjacent value will
be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new
Date(2014, 1, 1), both create a date for 2014-02-01 (note that the
month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0,
70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a
date for 2013-03-01T01:10:00.

You can calculate the difference(days) between two dates by using the code below.
var dateOne = new Date(firstDate);
var dateTwo = new Date(secondDate);
var dateDifference = Math.floor((dateTwo - dateOne) / 86400000);
console.log(dateDifference);

Related

Get the number of weeks between a start date and end date using js

As the title says I want to calculate the number of weeks between a start date and end date I'm a bit confuse can someone shed some light on me.
var start_date = new Date();
var end_date = new Date(2018,09,30);
use moment.js.
var start_date = new Date();
var end_date = new Date(2018,09,30);
change to format
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now, "DD/MM/YYYY HH:mm:ss").diff(moment(then, "DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
you can get total no of days, you can divide/7. so that you can get no of weeks.
function diff_weeks(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60 * 24 * 7);
return Math.abs(Math.round(diff));
}
dt1 = new Date(2018,09,25);
dt2 = new Date(2018,10,02);
alert(diff_weeks(dt1, dt2));
dt1 = new Date("September 25, 2018 08:11:00");
dt2 = new Date("October 02, 2018 08:11:00");
alert(diff_weeks(dt1, dt2));
this function will give you the difference in weeks
Try this code and number of weeks will be shown in dateArr also you will see here every week start- end. You can edit code for your needs.
var start = new Date(Date.UTC(2016, 09, 30, 0, 0, 0));
var end = new Date(Date.UTC(2016, 11, 02, 0, 0, 0));
var sDate;
var eDate;
var dateArr = [];
while(start <= end){
if (start.getDay() == 1 || (dateArr.length == 0 && !sDate)){
sDate = new Date(start.getTime());
}
if ((sDate && start.getDay() == 0) || start.getTime() == end.getTime()){
eDate = new Date(start.getTime());
}
if(sDate && eDate){
dateArr.push({'startDate': sDate, 'endDate': eDate});
sDate = undefined;
eDate = undefined;
}
start.setDate(start.getDate() + 1);
}
console.log(dateArr);
There are some really cool JavaScript libraries you can use for this. A nice lightweight one would be date-fns. I’ve linked the download link and I’ve written some example code for you from their documentation:
Download it/add it to your packages: https://date-fns.org
Documentation: https://date-fns.org/v1.29.0/docs/differenceInWeeks
Example:
// How many full weeks are between 5 July
// 2014 and 20 July 2014?
var result = differenceInWeeks(
new Date(2014, 6, 20),
new Date(2014, 6, 5)
)
//=> 2

JQDateRangeSlider change start/end value

I've been working with DateRangeSlider for a couple of days and now I'm using it as a time slider - fiddle
My problem is that the min time is 02:00 and it needs to be 00:00, and max time is 01:59 instead of 23:59.
If I changed the formatter values from
h = val.getHours(),
m = val.getMinutes();
to
h = val.getUTCHours(),
m = val.getUTCMinutes();
it displays the correct start-end hour but when I'm getting those values:
var values = $("#slider").dateRangeSlider('values');
var test = values.min;
it still gets the other values: 02:00 instead of 00:00.
Is there any way to format the min/max value but when the values are read to display the same hour?
You need to take into account the TimeZone and also the Daylight Saving Time (the Date() object is relied on them).
Your solution can be:
var minDateStr = "2014-01-01T00:00:00Z";
var maxDateStr = "2014-01-01T23:59:00Z";
var min2 = new Date(new Date(minDateStr).getTime() + new Date(minDateStr).getTimezoneOffset() * 60000),
max2 = new Date(new Date(maxDateStr).getTime() + new Date(maxDateStr).getTimezoneOffset() * 60000);
Here is a fix to your jsfiddle:
http://jsfiddle.net/z1govrt7/
I have updated format for date and time as below
var min2 = new Date(2014, 0, 1, 00, 00, 00),
max2 = new Date(2014, 11, 31, 23, 59, 59);
Please check http://jsfiddle.net/LJrYf/149/ fiddle now.
I have updated your code and now its working as expected.

Subtracting a specific date from today's date returns more than 3 days

Honestly, I don't know what's wrong. I'm using Flipclock javascript lib, and I'm trying to make a countdown to 15th January, 2015, 18:00 PM UTC. I tried many different approaches, and the one I currently have is which returns less numbers.
My code:
var clock;
$(document).ready(function (){
var nDate = new Date(2015, 01, 15, 18);
var currentDate = new Date();
var diff = (nDate.getTime() / 1000) - (currentDate.getTime() / 1000);
clock = $('.n-clock').FlipClock(diff, {
clockFace: 'DailyCounter',
autoStart: true,
countdown: true
});
});
Am I doing maths wrong? If so, please, tell me what's wrong.
Months are numbered from zero, so the following
var nDate = new Date(2015, 01, 15, 18);
Is February 15th.
Once you fix this, the result is correct. In Chrome:
> var nDate = new Date(2015, 0, 15, 18);
> var currentDate = new Date();
> var diff = (nDate.getTime() / 1000) - (currentDate.getTime() / 1000);
> diff / 24. / 3600.
< 2.894391319445438
(I.e. just under three days away.)

Javascript Days calculation between two days [duplicate]

This question already has answers here:
Why this operation with date (number of days between 2 dates) return this value?
(3 answers)
Closed 8 years ago.
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2013, 06, 30);
var secondDate = new Date(2013, 07, 01);
var diffDays = Math.round(Math.abs((secondDate.getTime() - firstDate.getTime()) / (oneDay)));
I run the above code the answer should be 1day. But It is giving me 2days.
Can you help me?
That's because months are 0 indexed in JavaScript. So your first date is in July, and the second one in August.
You're comparing with a month having 31 days, hence the correct difference of 2 days.
When I enter dates this way in JavaScript, I explicitly add the offset so that other coders don't read it wrong, it's too easy to make this error :
var firstDate = new Date(2013, 06 - 1, 30); // -1 due to the months being 0-indexed in JavaScript
var secondDate = new Date(2013, 07 - 1, 01);
Yes I had had my code "fixed"...
In javascript month is starting from 00-Jan since 05-june
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2013, 05, 30);
var secondDate = new Date(2013, 06, 01);
var diffDays = (secondDate- firstDate)/oneDay;
alert(diffDays);
To avoid confusion you can use like the following
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date('JUNE 30,2013');
var secondDate = new Date('JULY 01,2013');
var diffDays = (secondDate- firstDate)/oneDay;
alert(diffDays);

Countdown in Javascript

I would like to put on our company intranet page the number of days until the next payday, however - the payday dates aren't every 4 weeks etc. they will be similar to this:
1st January 2011
15th February 2011
12th March 2011
20th April 2011
...
Is it possible to have a javascript countdown clock that has the above dates listed, so once one date has passed it would then start counting down until the next calendar date?
I can find plenty of examples of scripts that countdown until a specific date but none that start counting down to the second date once the first has passed.
Thanks,
Dan
Put the dates in an array. Be careful, in Javascript the months are zero-based so ranging from 0 to 11. Iterate the array and when the date is bigger then today display the days in between:
var calcPayDate = function () {
var payDates = [];
payDates.push(new Date(2011, 0, 1));
payDates.push(new Date(2011, 1, 15));
payDates.push(new Date(2011, 2, 12));
payDates.push(new Date(2011, 3, 20));
var today = new Date();
for (var i = 0; i < payDates.length; i++) {
if (payDates[i] > today) {
document.getElementById('countdownDiv').innerHTML = calcDays(payDates[i], today);
break;
}
}
}
var calcDays = function(date1, date2) {
// The number of milliseconds in one day
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 = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms / ONE_DAY)
}
The calcDays function is an function found on this site
The days are put in a div which is called 'countdownDiv'.
Search the web for "JavaScript tutorial".
Meanwhile, here's some code to get you started:
var dates = [
new Date(2011, 0, 1), // note that format is year, month-1, day
new Date(2011, 1, 15), // don't ask me why
new Date(2011, 2, 12),
new Date(2011, 3, 20)
];
var now = new Date();
for (var i in dates) { // this is a foreach loop
if (now < dates[i]) {
document.write(Math.ceil((dates[i] - now) / 86400000));
break;
}
}

Categories

Resources