How to convert Date to String into the format yyyy-mm-dd in typescript

14,000

Assuming you are using Angular, you may import DatePipe, or FormatDate into your component.ts to handle that. You may read more about the various date/time formats you can pass as the parameters.

1) DatePipe:

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

export class SampleComponent implements OnInit {   

constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

Do not forget to add DatePipe to your providers in your module.

providers: [DatePipe]

2) formatDate:

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

export class SampleComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}
Share:
14,000
Shiny
Author by

Shiny

Updated on June 28, 2022

Comments

  • Shiny
    Shiny almost 2 years

    How to convert Date to String into the format yyyy-mm-dd in typescript

    Now I am getting the date as Fri Mar 24 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

    I only need date in the format "2017-03-24" from that and without any timezones and timezone conversions

    • Riscie
      Riscie over 5 years
      show us the code you have so far
    • ethanfar
      ethanfar over 5 years
      If you're using Angular, you should use the Date pipe. Look at this question, it's almost identical (assuming you're using Angular): stackoverflow.com/questions/35754586/…
  • Admin
    Admin over 5 years
    pipe can't be injected, they have to be instanciated (or instanciated then injected through a token or a factory)
  • Shiny
    Shiny over 5 years
    I tried the first method it worked. Thanks - @wentjun
  • wentjun
    wentjun over 5 years
    Cool, @Shiny! All the best with your project, mate!