MCPcopy Index your code
hub / github.com/TheAlgorithms/JavaScript / DateToDay

Function DateToDay

Conversions/DateToDay.js:28–70  ·  view source on GitHub ↗
(date)

Source from the content-addressed store, hash-verified

26]
27
28const DateToDay = (date) => {
29 // firstly, check that input is a string or not.
30 const dateStruct = parseDate(date)
31 let year = dateStruct.year
32 let month = dateStruct.month
33 let day = dateStruct.day
34
35 // In case of Jan and Feb:
36 // Year: we consider it as previous year
37 // e.g., 1/1/1987 here year is 1986 (-1)
38 // Month: we consider value as 13 & 14 respectively
39 if (month < 3) {
40 year--
41 month += 12
42 }
43
44 // divide year into century and the last two digits of the century
45 const yearDigits = year % 100
46 const century = Math.floor(year / 100)
47
48 /*
49 In mathematics, remainders of divisions are usually defined to always be positive;
50 As an example, -2 mod 7 = 5.
51 Many programming languages including JavaScript implement the remainder of `n % m` as `sign(n) * (abs(n) % m)`.
52 This means the result has the same sign as the numerator. Here, `-2 % 7 = -1 * (2 % 7) = -2`.
53
54 To ensure a positive numerator, the formula is adapted: `- 2 * century` is replaced with `+ 5 * century`
55 which does not alter the resulting numbers mod 7 since `7 - 2 = 5`
56
57 The following example shows the issue with modulo division:
58 Without the adaption, the formula yields `weekDay = -6` for the date 2/3/2014;
59 With the adaption, it yields the positive result `weekDay = 7 - 6 = 1` (Sunday), which is what we need to index the array
60 */
61 const weekDay =
62 (day +
63 Math.floor((month + 1) * 2.6) +
64 yearDigits +
65 Math.floor(yearDigits / 4) +
66 Math.floor(century / 4) +
67 5 * century) %
68 7
69 return daysNameArr[weekDay] // name of the weekday
70}
71
72// Example : DateToDay("18/12/2020") => Friday
73

Callers 1

DateToDay.test.jsFile · 0.90

Calls 1

parseDateFunction · 0.90

Tested by

no test coverage detected