how to get date in YYYY-MM-DD format in angular 2

17,710

Solution 1

You could simply use the Date Pipe

 <p>The time is {{currentDate | date:'yyyy-MM-dd'}}</p>

and in TS

export class App {

 currentDate: number = Date.now();

}

DEMO

Solution 2

  // To use date service 

   import { Injectable } from '@angular/core';

   @Injectable()

   export class DateService {

      public currentDate = new Date();

       getCurrentDateInApiFormat() {
          const date = currentDate;
          const month = ('0' + (date.getMonth() + 1)).slice(-2);
          const day = ('0' + date.getDate()).slice(-2);

          return [date.getFullYear(), month, day].join('-');
       }
   }    

Solution 3

The different date format can be achievable through moment.js library. You can just import/add it. and use the following syntax to convert your timestamp to date string.

moment.tz(this.value, 'GMT').format('yyyy-MM-dd HH:mm:ss');

Here tz is timezone.

Share:
17,710
Stacy J
Author by

Stacy J

Updated on June 04, 2022

Comments

  • Stacy J
    Stacy J almost 2 years

    I want to get date in the following format: YYYY-MM-DD.

    I wrote a date service in Angular2 based on this question: How do I get the current date in JavaScript?.

    I wanted to check if it is a correct implementation or if there exists a better way to achieve the goal.

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class DateService {
    private currentDate = new Date();
    
        getCurrentDateInApiFormat(): string{
            let day:any = this.currentDate.getDate();
            let month:any = this.currentDate.getMonth() + 1;
            let year:any = this.currentDate.getFullYear();
            let dateInApiFormat: string;
    
            if(day<10){
               day = '0' + day.toString();
            }
            if(month<10){
                month = '0' + month.toString();
            }
            dateInApiFormat = day + '-' + month + '-' + year.toString();
            return dateInApiFormat;
        }
    }