5

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;
    }
}
Will Barnwell
  • 4,049
  • 21
  • 34
Stacy J
  • 2,721
  • 15
  • 58
  • 92

3 Answers3

8

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

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
3
  // 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('-');
       }
   }    
zwessels
  • 617
  • 1
  • 10
  • 25
arul prince
  • 303
  • 1
  • 7
1

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.