/**
* Date Transformation Utility
*
* Transforms date strings into JavaScript Date objects and vice versa.
* Handles various date string formats and provides basic formatting options.
*/
const dateUtils = {
/**
* Converts a date string to a JavaScript Date object.
* Attempts to parse various date formats. Returns null if parsing fails.
* @param {string} dateString The date string to parse.
* @param {string} format (optional) The format of the date string (e.g., 'YYYY-MM-DD', 'MM/DD/YYYY').
* If not provided, attempts to auto-detect.
* @returns {Date|null} A JavaScript Date object or null if parsing fails.
*/
parseDate: (dateString, format) => {
if (!dateString) {
return null;
}
let date;
if (format) {
try {
date = new Date(dateString); //Try default parsing first
if (isNaN(date.getTime())) {
date = new Date(dateString); //Try again with more control
}
} catch (e) {
return null;
}
} else {
try {
date = new Date(dateString);
if (isNaN(date.getTime())) {
return null;
}
} catch (e) {
return null;
}
}
return date;
},
/**
* Converts a JavaScript Date object to a formatted date string.
* @param {Date} date The date object to format.
* @param {string} format The desired format string (e.g., 'YYYY-MM-DD', 'MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss').
* @returns {string} The formatted date string or an empty string if the date is invalid.
*/
formatDate: (date, format = 'YYYY-MM-DD') => {
if (!date) {
return '';
}
let year = date.getFullYear();
let month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
let day = String(date.getDate()).padStart(2, '0');
let formattedDate = format;
formattedDate = formattedDate.replace('YYYY', year);
formattedDate = formattedDate.replace('MM', month);
formattedDate = formattedDate.replace('DD', day);
formattedDate = formattedDate.replace('HH', String(date.getHours()).padStart(2, '0'));
formattedDate = formattedDate.replace('mm', String(date.getMinutes()).padStart(2, '0'));
formattedDate = formattedDate.replace('ss', String(date.getSeconds()).padStart(2, '0'));
return formattedDate;
},
/**
* Helper function to check if a date is valid.
* @param {Date} date
* @returns {boolean}
*/
isDateValid: (date) => {
return !isNaN(date.getTime());
}
};
export default dateUtils;
Add your comment