1. /**
  2. * Wraps date values with a custom wrapper object for error handling and manual overrides.
  3. *
  4. * @param {Date|string|number} dateValue The date value to wrap.
  5. * @returns {object} A wrapper object containing the original date value and methods for accessing/modifying it.
  6. * @throws {TypeError} If the input is not a valid date-like value.
  7. */
  8. function wrapDate(dateValue) {
  9. let date;
  10. try {
  11. date = new Date(dateValue); // Attempt to create a Date object.
  12. } catch (error) {
  13. throw new TypeError("Invalid date value: " + dateValue); //Re-throw as TypeError for consistency
  14. }
  15. // Create the wrapper object.
  16. return {
  17. value: date, // Store the original date value.
  18. toString: function() {
  19. return date.toISOString(); // Return a standardized string representation.
  20. },
  21. getFullYear: function() {
  22. return date.getFullYear();
  23. },
  24. getMonth: function() {
  25. return date.getMonth();
  26. },
  27. getDate: function() {
  28. return date.getDate();
  29. },
  30. setYear: function(year) {
  31. if (typeof year !== 'number') {
  32. throw new TypeError("Year must be a number");
  33. }
  34. this.value.setFullYear(year);
  35. },
  36. setMonth: function(month) {
  37. if (typeof month !== 'number' || month < 0 || month > 11) {
  38. throw new TypeError("Month must be a number between 0 and 11");
  39. }
  40. this.value.setMonth(month);
  41. },
  42. setDate: function(day) {
  43. if (typeof day !== 'number' || day < 1 || day > 31) {
  44. throw new TypeError("Day must be a number between 1 and 31");
  45. }
  46. this.value.setDate(day);
  47. },
  48. setHours: function(hours) {
  49. if (typeof hours !== 'number' || hours < 0 || hours > 23) {
  50. throw new TypeError("Hours must be a number between 0 and 23");
  51. }
  52. this.value.setHours(hours);
  53. },
  54. setMinutes: function(minutes) {
  55. if (typeof minutes !== 'number' || minutes < 0 || minutes > 59) {
  56. throw new TypeError("Minutes must be a number between 0 and 59");
  57. }
  58. this.value.setMinutes(minutes);
  59. },
  60. setSeconds: function(seconds) {
  61. if (typeof seconds !== 'number' || seconds < 0 || seconds > 59) {
  62. throw new TypeError("Seconds must be a number between 0 and 59");
  63. }
  64. this.value.setSeconds(seconds);
  65. },
  66. setMilliseconds: function(milliseconds) {
  67. if (typeof milliseconds !== 'number' || milliseconds < 0 || milliseconds > 999) {
  68. throw new TypeError("Milliseconds must be a number between 0 and 999");
  69. }
  70. this.value.setMilliseconds(milliseconds);
  71. },
  72. // Add more methods as needed for specific date manipulations.
  73. };
  74. }
  75. // Example usage:
  76. // const myDate = wrapDate("2023-10-26");
  77. // console.log(myDate.value.getFullYear());
  78. // myDate.setMonth(11);
  79. // console.log(myDate.toString());

Add your comment