Function: formatDateByArray()

formatDateByArray(array, formatter?): string

Formats a date based on an array of numbers, with optional formatting string

This function expects an array containing year, month, day, hour, minute, and second values. If the array is invalid or does not contain the necessary values, it logs a warning and returns 'Invalid Date'. The function uses the slice method to create a new array containing only the first six elements, and decrements the month value by 1 to convert it from a 1-based index to a 0-based index used by the Date object. It then creates a new Date object using the elements of the new array. If the date is invalid, it logs a warning and returns the date as a string. Finally, the function formats the date according to an optional formatting string and returns the formatted date string.

Parameters

array

number[]

The array representing the date. This array should contain year, month, day, hour, minute, and second values.

formatter?

string

Optional. A specific format string to format the date. Defaults to 'YYYY-MM-DD HH:mm:ss'.

Returns

string

The formatted date string.

Throws

Throws an error if the array is invalid or does not contain the necessary values.

Example

const dateArray = [2024, 2, 19, 10, 30, 0];
const formattedDate = formatDateByArray(dateArray, 'MMMM D, YYYY, h:mm A');
console.log(formattedDate);