Skip to content

Commit 766d35c

Browse files
add DateToDay method withour Date class
1 parent 95bc954 commit 766d35c

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Conversions/DateToDay.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
DateToDay Method
3+
----------------
4+
The DateToDay method takes a date in string format and
5+
returns the name of a day. The approach behind this method
6+
is very simple, we first take a string date and check
7+
whether their date is valid or not, if the date is valid
8+
then we do this But apply the algorithm shown below. The
9+
algorithm shown below gives us the number of the day and
10+
finally converts it to the name of the day.
11+
12+
Algorithm & Explanation : https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html
13+
*/
14+
15+
// March is taken as the first month of the year.
16+
const calcMonthList = {
17+
1: 11,
18+
2: 12,
19+
3: 1,
20+
4: 2,
21+
5: 3,
22+
6: 4,
23+
7: 5,
24+
8: 6,
25+
9: 7,
26+
10: 8,
27+
11: 9,
28+
12: 10
29+
}
30+
31+
// show the week day in a number : Sunday - Saturday => 0 - 6
32+
const daysNameList = { // weeks-day
33+
0: 'Sunday',
34+
1: 'Monday',
35+
2: 'Tuesday',
36+
3: 'Wednesday',
37+
4: 'Thursday',
38+
5: 'Friday',
39+
6: 'Saturday'
40+
}
41+
42+
const DateToDay = (date) => {
43+
// firstly, check that input is a string or not.
44+
if (typeof date !== 'string') {
45+
return new TypeError('Argument is not a string.')
46+
}
47+
// extarct the date
48+
const [day, month, year] = date.split('/').map((x) => Number(x))
49+
// check the data are valid or not.
50+
if ( day < 0 || day > 31 || month > 12 || month < 0) {
51+
return new TypeError('Date is not valid.')
52+
}
53+
// divide year to century and yearDigit value.
54+
const yearDigit = (year % 100)
55+
const century = Math.floor(year / 100)
56+
// Apply the algorithm shown above
57+
const weekDay = Math.abs((day + Math.floor((2.6 * calcMonthList[month]) - 0.2) - (2 * century) + yearDigit + Math.floor(yearDigit/4) + Math.floor(century/4)) % 7)
58+
// return the weekDay name.
59+
return daysNameList[weekDay];
60+
}
61+
62+
// Example : DateToDay("18/12/2020") => Friday
63+
64+
module.exports = DateToDay

0 commit comments

Comments
 (0)