/**
* Wraps date values with a custom wrapper object for error handling and manual overrides.
*
* @param {Date|string|number} dateValue The date value to wrap.
* @returns {object} A wrapper object containing the original date value and methods for accessing/modifying it.
* @throws {TypeError} If the input is not a valid date-like value.
*/
function wrapDate(dateValue) {
let date;
try {
date = new Date(dateValue); // Attempt to create a Date object.
} catch (error) {
throw new TypeError("Invalid date value: " + dateValue); //Re-throw as TypeError for consistency
}
// Create the wrapper object.
return {
value: date, // Store the original date value.
toString: function() {
return date.toISOString(); // Return a standardized string representation.
},
getFullYear: function() {
return date.getFullYear();
},
getMonth: function() {
return date.getMonth();
},
getDate: function() {
return date.getDate();
},
setYear: function(year) {
if (typeof year !== 'number') {
throw new TypeError("Year must be a number");
}
this.value.setFullYear(year);
},
setMonth: function(month) {
if (typeof month !== 'number' || month < 0 || month > 11) {
throw new TypeError("Month must be a number between 0 and 11");
}
this.value.setMonth(month);
},
setDate: function(day) {
if (typeof day !== 'number' || day < 1 || day > 31) {
throw new TypeError("Day must be a number between 1 and 31");
}
this.value.setDate(day);
},
setHours: function(hours) {
if (typeof hours !== 'number' || hours < 0 || hours > 23) {
throw new TypeError("Hours must be a number between 0 and 23");
}
this.value.setHours(hours);
},
setMinutes: function(minutes) {
if (typeof minutes !== 'number' || minutes < 0 || minutes > 59) {
throw new TypeError("Minutes must be a number between 0 and 59");
}
this.value.setMinutes(minutes);
},
setSeconds: function(seconds) {
if (typeof seconds !== 'number' || seconds < 0 || seconds > 59) {
throw new TypeError("Seconds must be a number between 0 and 59");
}
this.value.setSeconds(seconds);
},
setMilliseconds: function(milliseconds) {
if (typeof milliseconds !== 'number' || milliseconds < 0 || milliseconds > 999) {
throw new TypeError("Milliseconds must be a number between 0 and 999");
}
this.value.setMilliseconds(milliseconds);
},
// Add more methods as needed for specific date manipulations.
};
}
// Example usage:
// const myDate = wrapDate("2023-10-26");
// console.log(myDate.value.getFullYear());
// myDate.setMonth(11);
// console.log(myDate.toString());
Add your comment