Format current date time to "yyyy-MM-dd'T'HH:mm:ss.SSSZ" in Angular/Javascript/Typescript


Is there an easy way to format the date time in Angular/Typescript in "yyyy-MM-dd’T’HH:mm:ss.SSSZ"

I got the current date by doing

const currentDate = new Date().toLocaleDateString('What should I add here')

Can you please tell me what do I need to add here in the method to get in format of yyyy-MM-dd’T’HH:mm:ss.SSSZ


There are two ways to achieve this:

  1. The Angular way using DatePipe

In you component, you can inject DatePipe from @angular/common and call on the transform method to format date. Here is the list from Angular docs of options you can use to format date and time.

import { DatePipe } from '@angular/common';

class AppComponent {
  constructor(private datePipe: DatePipe) {}

  someMethod() {
    const date = this.datePipe.transform(new Date(), 'yyyy-MM-ddThh:mm:ss.SSSZ');

In the module, where you have defined this component, you need to provide DatPipe as providers

  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent ],
  providers: [ DatePipe ]
export class AppModule { }
  1. Second way would be to use native toISOString() method
const date = (new Date()).toISOString();

Answered By – Aakash Goplani

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.