1. /**
  2. * Date Transformation Utility
  3. *
  4. * Transforms date strings into JavaScript Date objects and vice versa.
  5. * Handles various date string formats and provides basic formatting options.
  6. */
  7. const dateUtils = {
  8. /**
  9. * Converts a date string to a JavaScript Date object.
  10. * Attempts to parse various date formats. Returns null if parsing fails.
  11. * @param {string} dateString The date string to parse.
  12. * @param {string} format (optional) The format of the date string (e.g., 'YYYY-MM-DD', 'MM/DD/YYYY').
  13. * If not provided, attempts to auto-detect.
  14. * @returns {Date|null} A JavaScript Date object or null if parsing fails.
  15. */
  16. parseDate: (dateString, format) => {
  17. if (!dateString) {
  18. return null;
  19. }
  20. let date;
  21. if (format) {
  22. try {
  23. date = new Date(dateString); //Try default parsing first
  24. if (isNaN(date.getTime())) {
  25. date = new Date(dateString); //Try again with more control
  26. }
  27. } catch (e) {
  28. return null;
  29. }
  30. } else {
  31. try {
  32. date = new Date(dateString);
  33. if (isNaN(date.getTime())) {
  34. return null;
  35. }
  36. } catch (e) {
  37. return null;
  38. }
  39. }
  40. return date;
  41. },
  42. /**
  43. * Converts a JavaScript Date object to a formatted date string.
  44. * @param {Date} date The date object to format.
  45. * @param {string} format The desired format string (e.g., 'YYYY-MM-DD', 'MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss').
  46. * @returns {string} The formatted date string or an empty string if the date is invalid.
  47. */
  48. formatDate: (date, format = 'YYYY-MM-DD') => {
  49. if (!date) {
  50. return '';
  51. }
  52. let year = date.getFullYear();
  53. let month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
  54. let day = String(date.getDate()).padStart(2, '0');
  55. let formattedDate = format;
  56. formattedDate = formattedDate.replace('YYYY', year);
  57. formattedDate = formattedDate.replace('MM', month);
  58. formattedDate = formattedDate.replace('DD', day);
  59. formattedDate = formattedDate.replace('HH', String(date.getHours()).padStart(2, '0'));
  60. formattedDate = formattedDate.replace('mm', String(date.getMinutes()).padStart(2, '0'));
  61. formattedDate = formattedDate.replace('ss', String(date.getSeconds()).padStart(2, '0'));
  62. return formattedDate;
  63. },
  64. /**
  65. * Helper function to check if a date is valid.
  66. * @param {Date} date
  67. * @returns {boolean}
  68. */
  69. isDateValid: (date) => {
  70. return !isNaN(date.getTime());
  71. }
  72. };
  73. export default dateUtils;

Add your comment