40

i use this line to get the current date

public current_date=new Date();

and i have got this result:

Wed Apr 26 2017 10:38:12 GMT+0100 (Afr. centrale Ouest)

how can i transform that to this format

YYYY-MM-DD

user3237201
  • 479
  • 1
  • 4
  • 13

8 Answers8

70

For Angular 5

app.module.ts

import {DatePipe} from '@angular/common';
.
.
.
providers: [DatePipe]

demo.component.ts

import { DatePipe } from '@angular/common';
.
.
constructor(private datePipe: DatePipe) {}

ngOnInit() {
   var date = new Date();
   console.log(this.datePipe.transform(date,"yyyy-MM-dd")); //output : 2018-02-13
}

more information angular/datePipe

Jayantha
  • 2,189
  • 1
  • 12
  • 13
  • 2
    I get this error: ERROR Error: InvalidPipeArgument: 'Missing locale data for the locale "de-DE".' for pipe 'DatePipe' – vsam Jun 05 '19 at 09:50
59

Example as per doc

@Component({
  selector: 'date-pipe',
  template: `<div>
    <p>Today is {{today | date}}</p>
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
    <p>The time is {{today | date:'jmZ'}}</p>
  </div>`
})
export class DatePipeComponent {
  today: number = Date.now();
}

Template

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mmss' }}        // output is '43:11'
{{dateObj  | date: 'dd/MM/yyyy'}} // 15/06/2015

To Use in your component.

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need. 
  }
}

In your app.module.ts

providers: [DatePipe,...] 

all you have to do is use this service now.

Parth Ghiya
  • 6,929
  • 2
  • 30
  • 37
12

Try this below code it is also works well in angular 2

<span>{{current_date | date: 'yyyy-MM-dd'}}</span>
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
  • actually i need it for a futur date comparaison in component – user3237201 Apr 26 '17 at 09:49
  • this `date: 'yyyy/MM/dd'` is an common filter way to formatting date using angular and you can create an constant to declare the format of `'yyyy/MM/dd'` and call the constant to your component – Ramesh Rajendran Apr 26 '17 at 09:50
  • could you please give me same exemple how to pass current date from template to component after formatting – user3237201 Apr 26 '17 at 10:00
  • just use `new Date(this.current_date.replace(/-/g, "/"));` or more details : http://stackoverflow.com/questions/3505693/difference-between-datedatestring-and-new-datedatestring – Ramesh Rajendran Apr 26 '17 at 10:02
6

Here is a very nice and compact way to do this, you can also change this function as your case needs:

result: 03.11.2017

//get date now function
    getNowDate() {
    //return string
    var returnDate = "";
    //get datetime now
    var today = new Date();
    //split
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //because January is 0! 
    var yyyy = today.getFullYear();
    //Interpolation date
    if (dd < 10) {
        returnDate += `0${dd}.`;
    } else {
        returnDate += `${dd}.`;
    }

    if (mm < 10) {
        returnDate += `0${mm}.`;
    } else {
        returnDate += `${mm}.`;
    }
    returnDate += yyyy;
    return returnDate;
}
Avtandil Kavrelishvili
  • 1,651
  • 3
  • 27
  • 37
6

Add the template and give date pipe, you need to use escape characters for the format of the date. You can give any format as you want like 'MM-yyyy-dd' etc.

template: '{{ current_date | date: \'yyyy-MM-dd\' }}',
Ani
  • 83
  • 1
  • 5
4

You can import

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

The standard format of the method.

formatDate(value: string | number | Date, format: string, locale: string, timezone?: string)

So here, all you have to do is pass your "current_date" in the method as value, then format (in your case "YYYY-MM-DD") and then locale, timezone is optional.

e.g.

formatDate(current_date,'yyyy-MM-dd',"en-US");

You will get your desired output.

For more reference, you can look into Angular-formatDate

Sharayu Nalvade
  • 261
  • 1
  • 2
  • 10
  • This works perfect, but to display it right it should be formatDate(current_date,'yyyy-MM-dd',"en-US") otherwise it shows January as 0, February as 1, March as 2, etc... – Danielle Dec 29 '21 at 18:06
0

Solution in ES6/TypeScript:

let d = new Date;
console.log(d, [`${d.getFullYear()}`, `0${d.getMonth()}`.substr(-2), `0${d.getDate()}`.substr(-2)].join("-"));
Alex Fortuna
  • 1,223
  • 12
  • 16
0

Check date if valid "date instanceof Date" so you can convert as your format otherwise return same as *Note:- We can use new Date() instead of moments

    convertIntoDate(value: string) {
     const date = new Date(value);
     if (date instanceof Date) {
       return moment(date, 'DD-MM-YYYY')
     } else {
       return value;
     }
    }
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 31 '22 at 07:43