Skip to content

Commit

Permalink
add stringToDate desc in utils
Browse files Browse the repository at this point in the history
  • Loading branch information
RgnDunes committed Jan 22, 2024
1 parent b819ee5 commit f2f36d0
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/modules/dateTime/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
/**
* Converts a string representation of a date into a Date object.
* The function supports various date and timestamp formats,
* including both American and European styles, with or without time components.
* If the provided string doesn't match any of the supported formats,
* the function throws an error.
*
* @param {string} dateString - The date string to be converted to a Date object.
* @returns {Date} A Date object representing the date and time specified in the dateString.
* @throws {Error} If the date format is not recognized.
*/
export const stringToDate = (dateString: string): Date => {
// List of supported date and timestamp formats.
const supportedDateFormats = [
// Date formats
{
Expand Down Expand Up @@ -107,19 +119,25 @@ export const stringToDate = (dateString: string): Date => {
}, // DD.MM.YYYY HH:MM:SS
];

// Iterate through each supported date format.
for (const format of supportedDateFormats) {
const match = dateString.match(format.regex);
if (match) {
// Extract year, month, and day from the matched groups.
const year = match[format.yearIndex];
const month = match[format.monthIndex];
const day = match[format.dayIndex];

// Extract time components if available, defaulting to '00' if not present.
const hour = format.hourIndex ? match[format.hourIndex] : '00';
const minute = format.minuteIndex ? match[format.minuteIndex] : '00';
const second = format.secondIndex ? match[format.secondIndex] : '00';

// Construct and return the Date object.
return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`);
}
}

// If no format matches, throw an error.
throw new Error('Date format not recognized');
};

0 comments on commit f2f36d0

Please sign in to comment.