Last active
August 7, 2023 17:57
-
-
Save tonycaputome/84263ed2557d414b639bbfba8d2d8595 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Your program must print string with the number of years and months and the total number of days between the dates. | |
* Dates are provided in dd.mm.yyyy format. | |
* You are not allowed to plug in JS libraries such as moment.js or date-fns directly into the code. All code need to be written in this file. | |
* | |
* Result must be shown as a string in years, months and total days. If years or months are 0, then it should not be displayed in the output. | |
* | |
* Example: | |
* Input: ['01.01.2000', '01.01.2016'] | |
* Output: | |
* '16 years, total 5844 days' | |
* | |
* Example 2: | |
* Input: ['01.11.2015', '01.02.2017'] | |
* | |
* Output: | |
* '1 year, 3 months, total 458 days' | |
*/ | |
const dates = [ | |
["01.01.2000", "01.01.2016"], | |
["01.01.2016", "01.08.2016"], | |
["01.11.2015", "01.02.2017"], | |
["17.12.2016", "16.01.2017"], | |
["01.01.2016", "01.01.2016"], | |
["28.02.2015", "13.04.2018"], | |
["28.01.2015", "28.02.2015"], | |
["17.03.2022", "17.03.2023"], | |
["17.02.2024", "17.02.2025"], | |
]; | |
// Receive string of dates one after each other | |
function outputDate(dates) { | |
let message = ``; | |
function format(date, separator = "-") { | |
const parts = date.split("."); | |
const year = parts[2]; | |
const month = parts[1]; | |
const day = parts[0]; | |
return new Date(`${year}${separator}${month}${separator}${day}`); | |
} | |
const startDate = format(dates[0]); | |
const endDate = format(dates[1]); | |
const diffInTime = endDate.getTime() - startDate.getTime(); | |
const diffInDays = Math.floor(diffInTime / (1000 * 3600 * 24)); | |
const diffInYears = Math.floor(diffInDays / 365); | |
const diffInMonths = new Date(endDate - startDate).getMonth(); | |
// create the final message | |
if (diffInYears > 0) { | |
message += `${diffInYears} year${diffInYears > 1 ? `s` : ``}, `; | |
} | |
if (diffInMonths > 0) { | |
message += `${diffInMonths} month${diffInMonths > 1 ? `s` : ``}, `; | |
} | |
message += `total ${diffInDays} days`; | |
return message; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment