Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert date into this 'yyyy-MM-dd' format in angular 2

Tags:

angular

ionic2

I want to convert current data into 'yyyy-MM-dd' format in .ts file. i template it can easily be done by using data pipe. how to do that in typescript.

In template:

{{date  | date:'yyyy-MM-dd'}} 

How to convert in this format 'yyyy-MM-dd' in typescript.

now i am just getting current date by using this.

this.date =  new Date(); 

but need to convert it into given format. Please guide how to do that... Thanks!

like image 821
Umar Rasheed Avatar asked Nov 02 '16 10:11

Umar Rasheed


People also ask

What is DatePipe in angular?

Angular date pipe used to format dates in angular according to the given date formats,timezone and country locale information. Using date pipe, we can convert a date object, a number (milliseconds from UTC) or an ISO date strings according to given predefined angular date formats or custom angular date formats.

How do I use DatePipe in HTML?

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


2 Answers

The date can be converted in typescript to this format 'yyyy-MM-dd' by using Datepipe

import { DatePipe } from '@angular/common' ... constructor(public datepipe: DatePipe){} ... myFunction(){  this.date=new Date();  let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd'); } 

and just add Datepipe in 'providers' array of app.module.ts. Like this:

import { DatePipe } from '@angular/common' ... providers: [DatePipe] 
like image 85
Umar Rasheed Avatar answered Sep 21 '22 08:09

Umar Rasheed


The same problem I faced in my project. Thanks to @Umar Rashed, but I am going to explain it in detail.

First, Provide Date Pipe from app.module:

providers: [DatePipe] 

Import to your component and app.module:

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

Second, declare it under the constructor:

constructor(     public datepipe: DatePipe   ) { 

Dates come from the server and parsed to console like this:

2000-09-19T00:00:00 

I convert the date to how I need with this code; in TypeScript:

this.datepipe.transform(this.birthDate, 'dd/MM/yyyy') 

Show from HTML template:

{{ user.birthDate }} 

and it is seen like this:

19/09/2000 

also seen on the web site like this: dates shown as it is filtered (click to see the screenshot)

like image 42
LuDeveloper Avatar answered Sep 20 '22 08:09

LuDeveloper