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
- 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
Format | Description | Example Output |
---|---|---|
HH:mm:ss | 24-hour format with seconds | 14:30:15 |
HH:mm | 24-hour format without seconds | 14:30 |
hh:mmA | 12-hour format with AM/PM | 02:30PM |
hh:mm:ssA | 12-hour format with seconds and AM/PM | 02:30:15PM |
HH:mm:ss.SSS | 24-hour format with milliseconds | 14: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"