@keerthana_lagadapati/date-utilities
Version:
The Date Utilities Module provides a collection of reusable functions to simplify working with dates in JavaScript.
53 lines (46 loc) • 1.79 kB
JavaScript
const DateUtils = {
// Formats a date object into a specific format (e.g., DD-MM-YYYY)
formatDate(date, format = "DD-MM-YYYY") {
const options = {
DD: String(date.getDate()).padStart(2, "0"),
MM: String(date.getMonth() + 1).padStart(2, "0"),
YYYY: String(date.getFullYear()),
HH: String(date.getHours()).padStart(2, "0"),
mm: String(date.getMinutes()).padStart(2, "0"),
ss: String(date.getSeconds()).padStart(2, "0"),
};
return format.replace(/DD|MM|YYYY|HH|mm|ss/g, (match) => options[match]);
},
// Adds a number of days to a given date
addDays(date, days) {
const newDate = new Date(date);
newDate.setDate(newDate.getDate() + days);
return newDate;
},
// Subtracts a number of days from a given date
subtractDays(date, days) {
const newDate = new Date(date);
newDate.setDate(newDate.getDate() - days);
return newDate;
},
// Checks if a given year is a leap year
isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
},
// Returns the weekday name for a date
getWeekday(date) {
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
return weekdays[date.getDay()];
},
// Calculates the difference in days between two dates
daysBetween(date1, date2) {
const diff = Math.abs(date1 - date2);
return Math.ceil(diff / (1000 * 60 * 60 * 24));
},
// Checks if a date is on a weekend
isWeekend(date) {
const day = date.getDay();
return day === 0 || day === 6; // Sunday (0) or Saturday (6)
},
};
export default DateUtils;