Time Formatting Parsing in JavaScript

JavaScript supports time formatting and parsing via built-in methods and libraries.

// We'll use the built-in Date object for time operations
const now = new Date();
console.log(now.toISOString());

// Parsing a date string
const t1 = new Date("2012-11-01T22:08:41+00:00");
console.log(t1);

// Custom formatting using built-in methods
console.log(now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true }));
console.log(now.toLocaleString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }));
console.log(now.toISOString());

// Parsing a custom format
const [hours, minutes, period] = "8:41 PM".split(/[:\s]/);
const t2 = new Date();
t2.setHours(period === 'PM' ? parseInt(hours) + 12 : parseInt(hours));
t2.setMinutes(parseInt(minutes));
console.log(t2);

// Numeric representation using extracted components
console.log(`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}T${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}-00:00`);

// Error handling for parsing
try {
    const invalidDate = new Date("8:41PM");
    console.log(invalidDate);
} catch (e) {
    console.log(e.message);
}

In JavaScript, we use the built-in Date object for working with dates and times. The Date object provides methods for formatting and parsing time.

The toISOString() method is used to format the date according to ISO 8601, which is similar to RFC3339.

For parsing, we can pass a date string directly to the Date constructor. JavaScript is more forgiving with date string formats compared to other languages.

Custom formatting in JavaScript is typically done using the toLocaleString() or toLocaleTimeString() methods, which allow specifying various options for the output format.

For purely numeric representations, we can extract the components of the date using methods like getFullYear(), getMonth(), etc., and format them manually.

Error handling for parsing invalid dates is done using try-catch blocks. JavaScript will create an “Invalid Date” object rather than throwing an error for many invalid formats.

When you run this script, you’ll see output similar to the following:

2023-06-10T12:34:56.789Z
2012-11-01T22:08:41.000Z
12:34 PM
Sat, Jun 10, 2023, 12:34:56 PM
2023-06-10T12:34:56.789Z
2023-06-10T20:41:00.000Z
2023-06-10T12:34:56-00:00
Invalid Date

Note that the exact output will depend on the current date and time when you run the script.