format a date in to the format 'yyyy-mm-dd hh:mm:ss' in typescript

To format a Date in typescript, you can use the toLocaleString() function or use a third-party library like moment.js.

Here's an example of how to use the toLocaleString() function to format a Date object:

index.ts
const date = new Date();
const formattedDate = date.toLocaleString('en-GB', { timeZone: 'UTC' })
  .replace(',', '')
  .replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$2-$1');
console.log(formattedDate);
192 chars
6 lines

Output: '2021-12-18 20:15:43'

If you prefer to use the moment.js library, here's an example:

index.ts
import * as moment from 'moment';

const date = new Date();
const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate);
154 chars
6 lines

Output: '2021-12-18 20:15:43'

Note that this solution requires you to install the moment.js library using a package manager like npm.

gistlibby LogSnag