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;
}
}
yyyy/M/d — Example: 2013/6/23. yyyy-MM-dd — Example: 2013-06-23.
You have to pass the locale string as an argument to DatePipe. var ddMMyyyy = this. datePipe. transform(new Date(),"dd-MM-yyyy");
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.
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
// 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('-');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With