forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateDayDifference.js
More file actions
Latest commit
62 lines (57 loc) · 1.72 KB
/
Copy pathDateDayDifference.js
File metadata and controls
62 lines (57 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
DateDayDifference Method
------------------------
DateDayDifference method calculates the number of days between two dates.
Algorithm & Explanation : https://ncalculators.com/time-date/date-difference-calculator.htm
*/
// Internal method for make calculations easier
constisLeap=(year)=>{
if(year%400===0)returntrue
elseif(year%100===0)returnfalse
elseif(year%4===0)returntrue
elsereturnfalse
}
constDateToDay=(dd,mm,yyyy)=>{
returnMath.floor(
365*(yyyy-1)+
(yyyy-1)/4-
(yyyy-1)/100+
(yyyy-1)/400+
dd+
(367*mm-362)/12+
(mm<=2 ? 0 : isLeap(yyyy) ? -1 : -2)
)
}
constDateDayDifference=(date1,date2)=>{
// firstly, check that both input are string or not.
if(typeofdate1!=='string'||typeofdate2!=='string'){
returnnewTypeError('Argument is not a string.')
}
// extract the first date
const[firstDateDay,firstDateMonth,firstDateYear]=date1
.split('/')
.map((ele)=>Number(ele))
// extract the second date
const[secondDateDay,secondDateMonth,secondDateYear]=date2
.split('/')
.map((ele)=>Number(ele))
// check the both data are valid or not.
if(
firstDateDay<0||
firstDateDay>31||
firstDateMonth>12||
firstDateMonth<0||
secondDateDay<0||
secondDateDay>31||
secondDateMonth>12||
secondDateMonth<0
){
returnnewTypeError('Date is not valid.')
}
returnMath.abs(
DateToDay(secondDateDay,secondDateMonth,secondDateYear)-
DateToDay(firstDateDay,firstDateMonth,firstDateYear)
)
}
// Example : DateDayDifference('17/08/2002', '10/10/2020') => 6630
export{DateDayDifference}