Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date format change angular 2

I need to change my date format, the problem is that I can't use moment.js, I need just to transform date from yyyy-mm-dd to dd-mm-yyyy. I use angular v 2.4.0.

like image 672
Jędrek Markowski Avatar asked Jun 30 '17 10:06

Jędrek Markowski


People also ask

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

Import DatePipe from angular/common and then use the below code: var datePipe = new DatePipe(); this. setDob = datePipe. transform(userdate, 'dd/MM/yyyy');

How do I change a datetime format in TypeScript?

You can format date/time in TypeScript, by using any of the built-in methods on the Date object or creating a reusable function that formats the date according to your requirements by leveraging built-in methods like getFullYear , getMonth , etc.


2 Answers

Use DatePipe pipe

date_expression | date[:format]

in your case

{{ date_expression | date:'dd-MM-yy' }}

How to use the pipe inside the component :

NgModule({
  ....
  providers: [DatePipe]
})

or

@Component({
   ....
  providers: [DatePipe]
})

In you component set it as a date variable

constructor(private datePipe: DatePipe) {
}

ngOnInit() {
    this.date = this.datePipe.transform(new Date(), 'dd-MM-yy');
}
like image 183
Yordan Nikolov Avatar answered Sep 17 '22 05:09

Yordan Nikolov


You can do it creating custom Pipe. Refer below code. For more info refer DatePipe Documentation.

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'customDateFormat',
})
export class customDateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'dd-mm-yyyy');
        return value;
    }
}

Add custom pipe in html as shown below:

{{currentDate | customDateFormat }}
like image 21
Nilesh Khisadiya Avatar answered Sep 18 '22 05:09

Nilesh Khisadiya