Formatting Dates in TypeScript to UTC

A guide on how to format dates in TypeScript to the specific format YYYY-MM-DDTHH:mm:ss+00:00.

To format a date in TypeScript to the specific format YYYY-MM-DDTHH:mm:ss+00:00, you can use the following code snippet:

1function formatDate(date: Date): string {
2    // Get the components of the date
3    const year = date.getUTCFullYear();
4    const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // Months are zero-based
5    const day = String(date.getUTCDate()).padStart(2, '0');
6    const hours = String(date.getUTCHours()).padStart(2, '0');
7    const minutes = String(date.getUTCMinutes()).padStart(2, '0');
8    const seconds = String(date.getUTCSeconds()).padStart(2, '0');
9
10    // Format the output
11    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}+00:00`;
12}
13
14// Example usage
15const newDate = new Date('2023-10-26T04:35:45Z'); // UTC time
16const formattedDate = formatDate(newDate);
17console.log(formattedDate); // Output: 2023-10-26T04:35:45+00:00
18

Explanation:

  1. Creating a Date Object: We create a new Date object with the desired date and time in UTC.
  2. Extracting Date Components:
    • We use getUTCFullYear(), getUTCMonth(), getUTCDate(), getUTCHours(), getUTCMinutes(), and getUTCSeconds() to get the respective components of the date in UTC.
    • We use padStart(2, '0') to ensure that month, day, hours, minutes, and seconds are always two digits.
  3. Formatting the Output: We concatenate the components into the desired format.

This will give you the output in the specified format, including the timezone offset.

Popular Articles

Prompts:

: lips drinking lemonade from the straw, pink background, 32K, beautifully color - coded, beautifully color graded, --ar 9:16 --v 6