d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Js Task: Calculate Days Until A Certain Date. > 100fg
Add Reply New Topic New Poll
Member
Posts: 14,925
Joined: Jan 3 2008
Gold: 135,879.75
Dec 5 2019 12:33am
Given a start date and an end date, write a function that calculates how many days it takes to reach the end date.

Code
startDateToEndDate({start: '12/5/19', end: '12/8/19'}) returns '3 days'
startDateToEndDate({start: '12/5/19', end: '1/1/19'}) returns '27 days'

Pay-out goes to the first answer posted in the thread.

This post was edited by kdog3682 on Dec 5 2019 12:33am
Member
Posts: 4,386
Joined: Oct 16 2006
Gold: 33,335.00
Dec 5 2019 04:59am
Code

<script type="text/javascript">

function findDays() {
var day1= document.getElementById("day1").value;
var day2= document.getElementById("day2").value;
var date1 = new Date(day1);
var date2=new Date(day2);

var one_day = 1000 * 60 * 60 * 24;
var d1 = date1.getTime();
var d2 = date2.getTime();
var diff = Math.abs(d1 - d2);
document.getElementById("days").value=Math.round(diff/one_day);
}

</script>

Date1 (yyyy-mm-dd): <input type="text" name="day1" id="day1" /> <br />
Date2 (yyyy-mm-dd): <input type="text" name="day2" id="day2" /> <br />
<input type="submit" value="calculate" onclick="findDays();"> <br /><br />
Days: <input type="text" name="days" id="days" readonly="true" />
Member
Posts: 2,619
Joined: May 21 2004
Gold: 21,934.00
Dec 9 2019 05:43pm
Quote (kdog3682 @ Dec 5 2019 02:33am)
Given a start date and an end date, write a function that calculates how many days it takes to reach the end date.

Code
startDateToEndDate({start: '12/5/19', end: '12/8/19'}) returns '3 days'
startDateToEndDate({start: '12/5/19', end: '1/1/19'}) returns '27 days'

Pay-out goes to the first answer posted in the thread.


edit: removed, just noticed you want this to work with dates that aren't in the right order. moment.

This post was edited by frixionburne on Dec 9 2019 05:45pm
Member
Posts: 2,619
Joined: May 21 2004
Gold: 21,934.00
Dec 9 2019 07:36pm
I think your second example is wrong. There are 338 some days between 1/1/19 and 12/5/19, not 27. 27 is from 12/5/2019 to 1/1/2020.

Code

function startDateToEndDate(obj) {
let startChunks = obj.start.split('/');
if(startChunks[2].length == 2) {
startChunks[2] = '20' + startChunks[2];
}
let startDate = new Date(startChunks.join('/'));

let endChunks = obj.end.split('/');
if(endChunks[2].length == 2) {
endChunks[2] = '20' + endChunks[2];
}
let endDate = new Date(endChunks.join('/'));
let diff = Math.abs(endDate - startDate);
let days = (diff / (60*60*24*1000))
return days;
}

let days = startDateToEndDate({start: '12/5/19', end: '12/8/19'});
// let days = startDateToEndDate({start: '12/5/19', end: '1/1/20'})
console.log(days);
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll