|
| 1 | +/* |
| 2 | +DateToDayCount Method |
| 3 | +--------------------- |
| 4 | +The DateToDayCount method takes a string date and tells |
| 5 | +how many days have passed from that date to the current date. |
| 6 | +
|
| 7 | +Problem source and Explanation : |
| 8 | + 1) http://wiki.hotdocs.com/index.php?title=Determine_Number_of_Days_Between_Two_Dates |
| 9 | + 2) https://wiki.scn.sap.com/wiki/display/Snippets/calculate+no+of+working+days+between+two+dates |
| 10 | +*/ |
| 11 | + |
| 12 | +const monthsNameList = { // create a monthsNameList for easy to use. |
| 13 | + 1: 'January', |
| 14 | + 2: 'February', |
| 15 | + 3: 'March', |
| 16 | + 4: 'April', |
| 17 | + 5: 'May', |
| 18 | + 6: 'June', |
| 19 | + 7: 'July', |
| 20 | + 8: 'August', |
| 21 | + 9: 'September', |
| 22 | + 10: 'October', |
| 23 | + 11: 'November', |
| 24 | + 12: 'December' |
| 25 | +} |
| 26 | + |
| 27 | +const DateToDayCount = (date) => { |
| 28 | + // firstly, check that input is a string or not. |
| 29 | + if (typeof date !== 'string') { |
| 30 | + return new TypeError('Argument is not a string.') |
| 31 | + } |
| 32 | + // extarct the date |
| 33 | + const [day, month, year] = date.split('/').map((x) => Number(x)) |
| 34 | + // check the data are valid or not. |
| 35 | + if (day > 31 || month > 12) { |
| 36 | + return new TypeError('Date is not valid.') |
| 37 | + } |
| 38 | + // create a base date for finding the actuale date. |
| 39 | + const baseDate = `${monthsNameList[month]} ${day}, ${year} 24:00:00` |
| 40 | + // use the Date class and make an object use of the base date. |
| 41 | + const inputDate = new Date(baseDate) |
| 42 | + // get the current date. |
| 43 | + const currentDate = new Date() |
| 44 | + // make some celculation for retrive the result. |
| 45 | + const diffTime = Math.abs(currentDate - inputDate) |
| 46 | + // convert time to day count. |
| 47 | + const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) |
| 48 | + return diffDays |
| 49 | +} |
| 50 | + |
| 51 | +module.exports = DateToDayCount |
0 commit comments