Javascript Days calculation between two days [duplicate] - javascript

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);

Related

Jquery is getting the incorrect difference between now and a future date

I tried to code a counter. For the first value it should show the difference between today and a future date. Out of some reason its showing an complete wrong difference. Do you know why?
The set future date 2th october 2020 should output a difference of 15 days and not over 40.
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2020, 10, 02);
const secondDate = new Date();
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
jQuery('#reducedaily').text(diffDays);
jQuery('.count, .count2').each(function () {
jQuery(this).prop('Counter',0).animate({
Counter: jQuery(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
if(jQuery(this).hasClass('count')){
jQuery(this).text(now.toFixed(0));
}
else{
jQuery(this).text(now.toFixed(1));
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="counterbackground" class="shadow">
<div class="counterdiv"><span class="count countervalue" id="reducedaily">239</span><br> <span class="counterdescription">Tage bis zum Event<br> (2.10.2020)</span></div>
</div>
When using the "month" parameter in the Date function in your jQuery, months are 0-indexed so they start at 0 instead of 1 as you might expect. So when you pass in 10, that actually represents November instead of October - this is why you got 30 extra days than you expected.
There are many ways to specify the date (see MDN Web Docs for Date). For example any of these will create a date object for 02 October 2020:
firstDate = new Date(2020, 09, 02); // when using the month param, it is (month-1)
firstDate = new Date("2020-10-02"); // note you DO use "10" in a date string
firstDate = new Date("10/02/2020"); // note mm/dd/yyyy format
firstDate = new Date("2 October 2020"); // or you can use text
Working Example with your code
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2020, 09, 02);
const secondDate = new Date();
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
jQuery('#reducedaily').text(diffDays);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="counterdiv"><span class="count countervalue" id="reducedaily">239</span><br> <span class="counterdescription">Tage bis zum Event<br>(2.10.2020)</span></div>
Working Example to test date strings
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const secondDate = new Date();
$("#testdate").on("click", function() {
dateStr = $("#date_to_check").val();
showDate(dateStr, "days_left");
});
showDate("2020-10-02", "days_left_test");
showDate("10/02/2020", "days_left_test");
showDate("2 October 2020", "days_left_test");
showDate("October 02 2020", "days_left_test");
function showDate(dateStr, elid){
document.getElementById(elid).innerHTML += "Date: <b>"+dateStr+" </b> Days left: <b>"+ Math.round(Math.abs((new Date(dateStr) - secondDate) / oneDay))+"</b><br>";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p>Test a date:</p>
<input type="text" id="date_to_check" placeholder="Enter date string">
<button id="testdate">Test</button>
<div id="days_left" style="margin-bottom: 20px"></div>
<p><b>More date Tests:</b></p>
<div id="days_left_test"></div>

How to calculate milliseconds since beginning of the day?

I've specified a specific time on a certain day. Now I wish to calculate the milliseconds from the beginning of that specific day to the set time of that day? I was hoping to do that with below code, but instead it shows nothing? What am I doing wrong?
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01").getTime();
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
I specify the countDownDate. Then I mark the beginning of that countDownDate into the variable countDownStart. Next I calculate the time passed since 00:00 of January 10 to 00:01 of January 10 by subtracting countDownStart from countDownDate. But no result is shown...
Your code has only one issue, and that is that you've assigned the result of .getTime() to countDownDate, which will be a number.
That's why JavaScript cannot call getFullYear, or any other function on that number, because those will be invalid calls.
To correct that, just remove the .getTime(), and it will work fine.
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
<div id="result">
<div>
Your logic is fine here. The only issue is this line here:
var countDownDate = new Date("January 10, 2018 00:01").getTime();
Since you used .getTime() the variable countDownDate is no longer a date. As such in the following statementcountDownDate.getFullYear() and forward isn't going to work. Simply remove .getTime() and it will work as expected:
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
console.log(countDownTime)

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

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);

Calculate date difference in javascript

I write the code below:
var _MS_PER_Day=24*60*60*1000;
var utc1 = Date.UTC(1900, 1, 1);
var utc2 = Date.UTC(2014,11,16);
var x = Math.ceil((utc2 - utc1) / _MS_PER_Day);
alert(x);
I want to calculate the date difference between the two dates.The actual date difference is 41957 but after running my code i get 41956 ,one date less.What is wrong with my code ?
Your code is calculating the difference between Feb 1, 1900 and Dec 16, 2014 (41956 days). The value month should be between 0...11 (where 0 is January). Correct the month numbers to get the expected result:
var _MS_PER_Day = 1000 * 60 * 60 * 24;
var utc1 = Date.UTC(1900, 0, 1); // Jan 01, 1900
var utc2 = Date.UTC(2014, 10, 16); // Nov 16, 2014
var x = Math.ceil((utc2 - utc1) / _MS_PER_Day);
alert(x); // 41957
This is an alternate code for the above which will give you 41957.
var date1 = new Date("1/1/1900");
var date2 = new Date("11/16/2014");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Reference :
Get difference between 2 dates in javascript?
The months are from 0 to 11 considering 0 as January.
You may also use getTime method to get the UTC timestamp in miliseconds.
var _MS_PER_Day = 1000 * 60 * 60 * 24;
var t1 = new Date(1900, 0, 1); // Jan 01, 1900
var t2 = new Date(2014, 10, 16); // Nov 16, 2014
var tdiff = Math.ceil((t2.getTime() - t1.getTime()) / _MS_PER_Day); // tdiff = 41957
http://www.w3schools.com/jsref/jsref_gettime.asp
I think you can use http://momentjs.com/
it give you the best result.
const a = new Date(YOUR_START_TIME),
b = new Date()
let diff = moment([b.getFullYear(), b.getMonth(), b.getDate()])
.diff(moment([a.getFullYear(), a.getMonth(), a.getDate()]), 'years', true)

JavaScript, get date of the next day [duplicate]

This question already has answers here:
Incrementing a date in JavaScript
(19 answers)
Closed 8 years ago.
I have the following script which returns the next day:
function today(i)
{
var today = new Date();
var dd = today.getDate()+1;
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
today = dd+'/'+mm+'/'+yyyy;
return today;
}
By using this:
today.getDate()+1;
I am getting the next day of the month (for example today would get 16).
My problem is that this could be on the last day of the month, and therefore end up returning 32/4/2014
Is there a way I can get the guaranteed correct date for the next day?
You can use:
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate()+1);
For example, since there are 30 days in April, the following code will output May 1:
var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000
var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000
See fiddle.
Copy-pasted from here:
Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
One-liner
const tomorrow = new Date(new Date().getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating
a new date):
var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow
= new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than
returning a new instance, so today.add(1, 'days') would modify today.
That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
Using Date object guarantees that. For eg if you try to create April 31st :
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

Categories

Resources