formatTime

A utility function to format JavaScript `Date` objects into various time formats. This function provides several time formats and allows for 24-hour or 12-hour (AM/PM) representations.
> function formatTime(date: Date, { format?: string }): string
Parameters
  • date (optional): A JavaScript Date object to format, defaults to current date.
  • format (optional): A string specifying the time format. Default is `hh:mmA`.
  • Returns: A string representing the formatted time.

Supported formats

FormatDescriptionExample Output
HH:mm:ss24-hour format with seconds14:30:15
HH:mm24-hour format without seconds14:30
hh:mmA12-hour format with AM/PM02:30PM
hh:mm:ssA12-hour format with seconds and AM/PM02:30:15PM
HH:mm:ss.SSS24-hour format with milliseconds14:30:15.123

Example

import { formatTime } from "@explita/daily-toolset";

const date = new Date();

// Format time in 24-hour format with seconds
console.log(formatTime(date, { format: "HH:mm:ss" })); // Example: "14:30:15"

// Format time in 12-hour format with AM/PM
console.log(formatTime(date, { format: "hh:mmA" })); // Example: "02:30PM"

// Format time in 24-hour format without seconds
console.log(formatTime(date, { format: "HH:mm" })); // Example: "14:30"

// Format time in 12-hour format with seconds and AM/PM
console.log(formatTime(date, { format: "hh:mm:ssA" })); // Example: "02:30:15PM"

// Format time in 24-hour format with milliseconds
console.log(formatTime(date, { format: "HH:mm:ss.SSS" })); // Example: "14:30:15.123"