Skip to main content

Date & Time Utilities

A comprehensive collection of date and time manipulation, validation, and formatting utilities built on top of date-fns for the WorkPayCore frontend application.

Format Constants

Standard Format Strings

export const dayMonthYearTimeFormat = 'do MMM, yyyy p'; // "1st Jan, 2024 2:30 PM"
export const dayMonthYearFormat = 'do MMM, yyyy'; // "1st Jan, 2024"
export const yearMonthDayFormat = 'yyyy-MM-dd'; // "2024-01-01"

Validation Functions

isValidDateString(...args)

Validates if one or more date strings are valid ISO date strings.

Parameters:

  • ...args (string[]): Variable number of date strings to validate

Returns:

  • boolean: True if all provided date strings are valid

Example:

isValidDateString('2024-01-01');
// Returns: true

isValidDateString('2024-01-01', '2024-12-31');
// Returns: true

isValidDateString('2024-01-01', 'invalid-date');
// Returns: false

isValidDateString('not-a-date');
// Returns: false

Use Cases:

  • Validating API response dates
  • Form input validation
  • Bulk date validation

isValidYear(year)

Validates if a given year is valid within the context of a date.

Parameters:

  • year (number): The year to validate

Returns:

  • boolean: True if the year is valid

Example:

isValidYear(2024); // Returns: true
isValidYear(1900); // Returns: true
isValidYear(null); // Returns: false
isValidYear(-1); // Returns: false

Use Cases:

  • Form validation for birth years
  • Date range validation
  • Historical data validation

isValidMonth(month)

Validates if a given month name is one of the 12 possible month names.

Parameters:

  • month (string): The month name to validate

Returns:

  • boolean: True if the month is valid

Example:

isValidMonth('February'); // Returns: true
isValidMonth('January'); // Returns: true
isValidMonth('Invalid'); // Returns: false
isValidMonth(null); // Returns: false

Use Cases:

  • Month name validation in forms
  • Data import validation
  • Localization validation

Formatting Functions

dateFormatterUtil(date, formatString?)

Formats an ISO date string using a specified format pattern.

Parameters:

  • date (string): ISO date string to format
  • formatString (string, optional): Format pattern (default: dayMonthYearTimeFormat)

Returns:

  • string | null: Formatted date string or null if invalid

Example:

dateFormatterUtil('2024-01-01T14:30:00Z');
// Returns: "1st Jan, 2024 2:30 PM"

dateFormatterUtil('2024-01-01T14:30:00Z', 'yyyy-MM-dd');
// Returns: "2024-01-01"

dateFormatterUtil('invalid-date');
// Returns: null

Use Cases:

  • Displaying API dates in UI
  • Consistent date formatting across app
  • User-friendly date presentation

formatDateTime(date)

Formats a date string into multiple commonly used formats.

Parameters:

  • date (string): ISO date string to format

Returns:

  • object: Object containing multiple formatted versions or empty object if invalid

Example:

formatDateTime('2024-01-01T14:30:00Z');
// Returns: {
// formattedDateWithTime: "1st Jan, 2024 2:30 PM",
// formattedDate: "1st Jan, 2024",
// formattedTime: "2:30 PM"
// }

formatDateTime('invalid-date');
// Returns: {}

Use Cases:

  • Comprehensive date display options
  • Different format requirements in same component
  • Flexible date presentation

formatTime(date)

Formats a time string into both 12-hour and 24-hour formats.

Parameters:

  • date (string): Time string in 'HH:mm:ss' format

Returns:

  • object: Object containing both time formats

Example:

formatTime('14:30:00');
// Returns: {
// twelveHoursFormat: "2:30 PM",
// twentyFourHourFormat: "14:30"
// }

formatTime('09:15:30');
// Returns: {
// twelveHoursFormat: "9:15 AM",
// twentyFourHourFormat: "09:15"
// }

Use Cases:

  • Time display preferences
  • Different time format requirements
  • User configuration options

WPDateObjectFormatUtil(date, formatString?)

Formats a Date object, timestamp, or date string using a specified format pattern.

Parameters:

  • date (string | number | Date): Date input to format
  • formatString (string, optional): Format pattern (default: dayMonthYearTimeFormat)

Returns:

  • string | null: Formatted date string or null if invalid

Example:

WPDateObjectFormatUtil(new Date('2024-01-01'));
// Returns: "1st Jan, 2024 12:00 AM"

WPDateObjectFormatUtil(1704067200000, 'yyyy-MM-dd');
// Returns: "2024-01-01"

WPDateObjectFormatUtil('2024-01-01T14:30:00Z', 'MMM do, yyyy');
// Returns: "Jan 1st, 2024"

Use Cases:

  • Formatting Date objects from JavaScript
  • Timestamp formatting
  • Flexible date input handling

Parsing Functions

dateParser(date)

Safely parses an ISO date string into a Date object.

Parameters:

  • date (string): ISO date string to parse

Returns:

  • Date | null: Parsed Date object or null if invalid

Example:

dateParser('2024-01-01T14:30:00Z');
// Returns: Date object

dateParser('invalid-date');
// Returns: null

dateParser('');
// Returns: null

Use Cases:

  • Safe date parsing from API
  • Converting strings to Date objects
  • Preventing invalid date errors

getBackendDateFormat(dateString, dateFormat?)

Formats a date for backend API consumption.

Parameters:

  • dateString (string | Date): Date to format
  • dateFormat (string, optional): Format pattern (default: yearMonthDayFormat)

Returns:

  • string | null: Formatted date string or null if invalid

Example:

getBackendDateFormat(new Date('2024-01-01'));
// Returns: "2024-01-01"

getBackendDateFormat('2024-01-01T14:30:00Z', 'yyyy-MM-dd');
// Returns: "2024-01-01"

Use Cases:

  • API payload preparation
  • Database date formatting
  • Backend integration

Utility Functions

dateSuperscript(d)

Returns the appropriate ordinal suffix for a given day number.

Parameters:

  • d (number): Day number (1-31)

Returns:

  • string: Ordinal suffix ('st', 'nd', 'rd', 'th')

Example:

dateSuperscript(1); // Returns: "st"
dateSuperscript(2); // Returns: "nd"
dateSuperscript(3); // Returns: "rd"
dateSuperscript(4); // Returns: "th"
dateSuperscript(21); // Returns: "st"
dateSuperscript(22); // Returns: "nd"

Use Cases:

  • Creating ordinal date displays
  • Custom date formatting
  • User-friendly date presentation

getMonthIndex(month)

Returns the zero-based index of a month name.

Parameters:

  • month (string): Month name

Returns:

  • number: Month index (0-11) or -1 if invalid

Example:

getMonthIndex('January'); // Returns: 0
getMonthIndex('February'); // Returns: 1
getMonthIndex('December'); // Returns: 11
getMonthIndex('Invalid'); // Returns: -1

Use Cases:

  • Month name to index conversion
  • Calendar operations
  • Date construction from month names

adjustToNoon(date)

Adjusts a date to 12:00 PM (noon) to avoid timezone issues.

Parameters:

  • date (Date): Date to adjust

Returns:

  • Date: New Date object set to noon

Example:

const date = new Date('2024-01-01T08:30:00Z');
const noonDate = adjustToNoon(date);
// Returns: Date object set to 2024-01-01 12:00:00

Use Cases:

  • Avoiding timezone calculation issues
  • Consistent date comparisons
  • Date picker operations

Advanced Functions

calculateMaxEndDate(startDate, trainingDuration, durationUnit)

Calculates the maximum end date for a training or event based on duration.

Parameters:

  • startDate (Date): Starting date
  • trainingDuration (number): Duration value
  • durationUnit (string): Unit of duration ('days', 'weeks', 'months', 'years')

Returns:

  • Date: Calculated end date

Example:

const startDate = new Date('2024-01-01');
const endDate = calculateMaxEndDate(startDate, 2, 'weeks');
// Returns: Date object for 2024-01-15 (2 weeks later)

const endDate2 = calculateMaxEndDate(startDate, 3, 'months');
// Returns: Date object for 2024-04-01 (3 months later)

Use Cases:

  • Training program planning
  • Event scheduling
  • Deadline calculations

formatSameMonthYearDateDisplay(startDate, endDate)

Formats date ranges intelligently based on whether they share the same month/year.

Parameters:

  • startDate (string): ISO start date string
  • endDate (string): ISO end date string

Returns:

  • string: Intelligently formatted date range

Example:

// Same month and year
formatSameMonthYearDateDisplay('2024-01-01', '2024-01-15');
// Returns: "1st - 15th Jan, 2024"

// Different months, same year
formatSameMonthYearDateDisplay('2024-01-01', '2024-02-15');
// Returns: "1st Jan - 15th Feb, 2024"

// Different years
formatSameMonthYearDateDisplay('2023-12-01', '2024-01-15');
// Returns: "1st Dec, 2023 - 15th Jan, 2024"

Use Cases:

  • Date range displays
  • Event duration formatting
  • Compact date range presentation

formatTo12HourTime(date)

Converts a Date object to 12-hour time format.

Parameters:

  • date (Date): Date object to format

Returns:

  • string: Time in 12-hour format

Example:

const date = new Date('2024-01-01T14:30:00');
formatTo12HourTime(date);
// Returns: "2:30 PM"

const morningDate = new Date('2024-01-01T09:15:00');
formatTo12HourTime(morningDate);
// Returns: "9:15 AM"

Use Cases:

  • Time display in UI
  • User-friendly time formatting
  • 12-hour time preference

getDateTime(date, time)

Combines separate date and time values into a single Date object.

Parameters:

  • date (string | Date): Date component
  • time (string): Time component

Returns:

  • Date: Combined Date object

Example:

getDateTime('2024-01-01', '14:30:00');
// Returns: Date object for 2024-01-01 14:30:00

getDateTime(new Date('2024-01-01'), '09:15:30');
// Returns: Date object for 2024-01-01 09:15:30

Use Cases:

  • Combining separate date/time inputs
  • Creating timestamps from components
  • Form data processing

Advanced Usage Examples

Complete Date Validation Pipeline

const validateDateRange = (startDate, endDate) => {
// Validate individual dates
if (!isValidDateString(startDate, endDate)) {
return { valid: false, error: 'Invalid date format' };
}

// Parse dates for comparison
const start = dateParser(startDate);
const end = dateParser(endDate);

if (!start || !end) {
return { valid: false, error: 'Unable to parse dates' };
}

// Check date order
if (start >= end) {
return { valid: false, error: 'End date must be after start date' };
}

return { valid: true, dates: { start, end } };
};

Comprehensive Date Display Component

const DateDisplay = ({
isoDateString,
showTime = true,
format = 'friendly',
}) => {
if (!isValidDateString(isoDateString)) {
return <span>Invalid Date</span>;
}

const dateFormats = formatDateTime(isoDateString);

if (format === 'friendly') {
return (
<span>
{showTime
? dateFormats.formattedDateWithTime
: dateFormats.formattedDate}
</span>
);
}

return <span>{dateFormatterUtil(isoDateString, format)}</span>;
};

Training Schedule Calculator

const calculateTrainingSchedule = (
startDate,
sessions,
sessionDuration,
unit,
) => {
const schedule = [];
let currentDate = dateParser(startDate);

for (let i = 0; i < sessions; i++) {
const sessionStart = new Date(currentDate);
const sessionEnd = calculateMaxEndDate(sessionStart, sessionDuration, unit);

schedule.push({
session: i + 1,
startDate: WPDateObjectFormatUtil(sessionStart, 'yyyy-MM-dd'),
endDate: WPDateObjectFormatUtil(sessionEnd, 'yyyy-MM-dd'),
displayRange: formatSameMonthYearDateDisplay(
sessionStart.toISOString(),
sessionEnd.toISOString(),
),
});

// Move to next session start date
currentDate = new Date(sessionEnd);
currentDate.setDate(currentDate.getDate() + 1);
}

return schedule;
};

Performance Considerations

  • Date Parsing: O(1) - constant time for individual dates
  • Date Formatting: O(1) - constant time operations
  • Validation: O(n) where n is the number of dates being validated
  • Range Calculations: O(1) - simple arithmetic operations

Error Handling

All date utilities handle edge cases gracefully:

  • Invalid Dates: Return null or empty objects instead of throwing errors
  • Null/Undefined Inputs: Safely handle missing date values
  • Format Errors: Gracefully handle malformed date strings
  • Timezone Issues: Use date-fns for consistent timezone handling


Dependencies

This module uses date-fns for robust date manipulation:

import {
isSameMonth,
isSameYear,
parse,
add,
format,
getMonth,
isValid,
parseISO,
setHours,
isThisYear,
} from 'date-fns';