Created
December 22, 2023 11:11
-
-
Save PabloAballe/182cfd018f70ca1d1cb2cf0a21d23f53 to your computer and use it in GitHub Desktop.
Date and Time Functions: Brief Description: Collection of functions to handle and format dates and times in JavaScript.
This file contains hidden or 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
| /** | |
| * Date and Time Functions | |
| * Brief Description: Collection of functions to handle and format dates and times in JavaScript. | |
| * | |
| * Author: Pablo Aballe | |
| * Date: 2023-12-22 | |
| */ | |
| /** | |
| * Formats a Date object into a readable string. | |
| * @param {Date} date - The date to format. | |
| * @returns {string} - Formatted date string. | |
| */ | |
| function formatDate(date) { | |
| return date.toISOString().substring(0, 10); // Returns format: YYYY-MM-DD | |
| } | |
| /** | |
| * Calculates the difference in days between two dates. | |
| * @param {Date} date1 - The first date. | |
| * @param {Date} date2 - The second date. | |
| * @returns {number} - Number of days between the dates. | |
| */ | |
| function daysBetween(date1, date2) { | |
| const msPerDay = 24 * 60 * 60 * 1000; | |
| return Math.abs((date1 - date2) / msPerDay); | |
| } | |
| /** | |
| * Adds a specified number of days to a date. | |
| * @param {Date} date - The original date. | |
| * @param {number} days - Number of days to add. | |
| * @returns {Date} - New date with added days. | |
| */ | |
| function addDays(date, days) { | |
| const newDate = new Date(date); | |
| newDate.setDate(newDate.getDate() + days); | |
| return newDate; | |
| } | |
| // Usage Examples | |
| console.log(formatDate(new Date())); // Outputs today's date in YYYY-MM-DD format | |
| console.log(daysBetween(new Date('2023-01-01'), new Date('2023-12-31'))); // Outputs the number of days between two dates | |
| console.log(addDays(new Date(), 10)); // Outputs the date 10 days from today | |
| // Additional Notes: | |
| // These functions provide basic date manipulation and formatting. More complex operations may require additional logic or libraries like Moment.js or date-fns. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment