Say you want to parse this date: 2023-05-31 T06:52:03Z
.
Note: This date is non-standard as it has a space
between 31
and T
// npm install date-fns date-fns-tz
import { parseISO } from 'date-fns';
import { utcToZonedTime, format as utcFormat } from 'date-fns-tz';
const dateObject: Date = parseISO("2023-05-31T06:52:03Z");
const dateInUTC = utcToZonedTime(dateObject, 'UTC');
// Format the date into UTC
const formattedDateInUTC = utcFormat(dateInUTC, "yyyy-MM-dd_HH.mm.ss.SSS'Z'", { timeZone: 'UTC' });
console.log(`formattedDateInUTC=${formattedDateInUTC}`) // 2023-05-31_06.52.03.000Z
const year = dateObject.getUTCFullYear();
const month = dateObject.getUTCMonth() + 1; // Months are 0-based
const day = dateObject.getUTCDate();
const hour = dateObject.getUTCHours();
const minute = dateObject.getUTCMinutes();
const second = dateObject.getUTCSeconds();
const millisecond = dateObject.getUTCMilliseconds();
console.log(`Year: ${year}`); // 2023
console.log(`Month: ${month}`); // 5
console.log(`Day: ${day}`); // 31
console.log(`Hour: ${hour}`); // 6
console.log(`Minute: ${minute}`); // 52
console.log(`Second: ${second}`); // 3
console.log(`Millisecond: ${millisecond}`); // 0