How to format a UTC date as a `YYYY-MM-DD hh:mm:ss …
Hello MicrslavRalevic,
Using date-fns Library : The date-fns library provides a straightforward way to format dates.
Install date-fns: npm install date-fns
Format the date in your Node.js code: import { format } from ‘date-fns’;
const date = new Date(); // Replace with your UTC date const formattedDate = format(date, ‘yyyy-MM-dd HH:mm:ss’); console.log(formattedDate);
In this approach, the format function from date-fns is used to convert the Date object into the desired string format.
Hey Miroslav,
Using moment Library : The moment library is another popular choice for date formatting.
Install moment: npm install moment
Format the date in your Node.js code:
import moment from ‘moment’;
const date = new Date(); // Replace with your UTC date const formattedDate = moment(date).format(‘YYYY-MM-DD HH:mm:ss’); console.log(formattedDate);
In this approach, moment provides a convenient method to format dates.
Hey MiroslavRalevic, Using Vanilla JavaScript with Manual Formatting : If you prefer not to use external libraries, you can format the date manually using vanilla JavaScript. const date = new Date(); // Replace with your UTC date
const pad = (n: number) => (n < 10 ? ‘0’ + n : n);
const formattedDate = [ date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate()) ].join(‘-’) + ’ ’ + [ pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()) ].join(‘:’);
console.log(formattedDate);
In this approach, you manually construct the formatted string by extracting and padding the date components.