6

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.

0

3 Answers 3

32

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');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ye, it look very easy, but is it possible to put this {{ date_expression | date:'dd-MM-yy' }} into variable(I need to put it on class later) I mean variable= {{ date_expression | date:'dd-MM-yy' }}
5

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 }}

3 Comments

Ye, it look very easy, but is it possible to put this {{ date_expression | date:'dd-MM-yy' }} into variable(I need to put it on class later) I mean variable= {{ date_expression | date:'dd-MM-yy' }}
@JędrekMarkowski : But if you want to use any library in future like momentJS or others. You have to modify in one place to get effect on all pages. Any ways you get a solution. :-)
its throwing error customDateFormat could not be found
1

What you can do is create a function like this

function formatDate() {
    let addZeroToLoneFigure = (n) => n.toString().length === 1 ? '0' + n : n.toString();
    let format = 'DD-MM-YYYY';
    let d= new Date();
    format.replace('DD', addZeroToLoneFigure(d.getDate()));
    format.replace('MM', addZeroToLoneFigure(d.getMonth() + 1));
    format.replace('YYYY', addZeroToLoneFigure(d.getFullYear()));
    return format;
}

2 Comments

Ye, it look very easy, but is it possible to put this {{ date_expression | date:'dd-MM-yy' }} into variable(I need to put it on class later) I mean variable= {{ date_expression | date:'dd-MM-yy' }}
I didn't get what you want, but my function returns something, so just do let myVar = this.formatDate();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.