Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 489
Stacy J Avatar asked Sep 05 '17 18:09

Stacy J


People also ask

How do you format a date in mm dd yyyy?

yyyy/M/d — Example: 2013/6/23. yyyy-MM-dd — Example: 2013-06-23.

What is the right way to convert format of date using date pipe in angular?

You have to pass the locale string as an argument to DatePipe. var ddMMyyyy = this. datePipe. transform(new Date(),"dd-MM-yyyy");

What is DatePipe in angular?

DatePipe is used to format a date value according to locale rules. Syntax: {{ value | date }} Approach: Create the angular app that to be used. There is no need for any import for the DatePipe to be used.


2 Answers

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

like image 51
Sajeetharan Avatar answered Sep 20 '22 04:09

Sajeetharan


  // 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('-');
       }
   }    
like image 38
arul prince Avatar answered Sep 22 '22 04:09

arul prince