93

I want to convert current date into 'yyyy-MM-dd' format in .ts file. In template it can easily be done by using date 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?

I am just getting current date by using this.

this.date =  new Date();

but I need to convert it into the given format.

Oli
  • 9,766
  • 5
  • 25
  • 46
Umar Rasheed
  • 4,323
  • 4
  • 16
  • 26
  • 1
    Duplicate of http://stackoverflow.com/questions/35144821/angular-2-use-pipes-in-services – Shil Nevado Nov 02 '16 at 10:07
  • 1
    Possible duplicate of [How to format date as dd/MM/yyyy in Angular 2 using pipes?](http://stackoverflow.com/questions/35754586/how-to-format-date-as-dd-mm-yyyy-in-angular-2-using-pipes) – Ivar Reukers Nov 02 '16 at 11:16
  • i tried both but not working it might be due to some changes in Angular 2 final. because mentioned duplicates are from beta – Umar Rasheed Nov 02 '16 at 11:44
  • This question is answered in the question linked by @Shil, read the second answer which utilizes constructor injection. The one thing not present in that answer is the datepipe needs to be listed in the providers of the component or service if using DI. – silentsod Nov 02 '16 at 17:39
  • What is your version of angular? I tested in [rc.2 version](http://plnkr.co/edit/vMSP5cT1XTAWi7oYBYmm?p=preview) that I [quote in my answer](http://stackoverflow.com/a/37931071/2290538) and [angular current version 2.1.1](http://plnkr.co/edit/f7Wih8ceKHQUDHKmYCpQ?p=preview), and its format standard works properly. This has been resolved in version rc.2 [as I quote here](http://stackoverflow.com/a/37931071/2290538). If your angular is after rc.2 this should work if lower you should consider an alternative [as is](http://stackoverflow.com/a/37859544/2290538) or to upgrade version of angular. – Fernando Leal Nov 03 '16 at 11:10
  • My version is angular 2.0.0 final. – Umar Rasheed Nov 04 '16 at 13:10

8 Answers8

194

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]
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Umar Rasheed
  • 4,323
  • 4
  • 16
  • 26
26

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)

LuDeveloper
  • 618
  • 6
  • 12
  • 3
    Briliant , This is what developer need, not to append single day, month or year to create own format. cheers! mate... Thanks. – Amrish Kakadiya Dec 04 '20 at 18:25
17

You can also use formatDate

let formattedDt = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ssZZZZZ', 'en_US')
Abhishek Soni
  • 563
  • 1
  • 6
  • 17
15

A simple solution would be to just write

this.date = new Date().toLocaleDateString();

date .toLocaleDateString() time .toLocaleTimeString() both .toLocaleString()

Hope this helps.

Ahmed Hamed
  • 411
  • 4
  • 9
  • Friend I can get data perfect ex: 30/08/2018 (date from Brazil), but if I want get only day or month or only years , how to do this ? – Rafael Moura Aug 30 '18 at 03:53
  • what you're looking for has been answered in the following [**SO question**](https://stackoverflow.com/questions/2013255/how-to-get-year-month-day-from-a-date-object) – Ahmed Hamed Sep 28 '18 at 22:28
9

You can also try this.

consider today's date '28 Dec 2018'(for example)

 this.date = new Date().toISOString().slice(0,10); 

new Date() we get as: Fri Dec 28 2018 11:44:33 GMT+0530 (India Standard Time)

toISOString will convert to : 2018-12-28T06:15:27.479Z

slice(0,10) we get only first 10 characters as date which contains yyyy-mm-dd : 2018-12-28.

Akj
  • 7,038
  • 3
  • 28
  • 40
Viveka
  • 175
  • 2
  • 12
  • 1
    Note that the ISO string will be in the GMT timezone, so your day might be off-by-one either way, depending on your timezone. – mik01aj Nov 12 '20 at 17:23
  • This answer is wrong. You completely missed the timezone. Have you tried the `2018-12-31T23:55:00.000Z`? – youhans Aug 14 '21 at 14:38
1

const formatDate=(dateObj)=>{
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const dateOrdinal=(dom)=> {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};
return dateOrdinal(dateObj.getDate())+', '+days[dateObj.getDay()]+' '+ months[dateObj.getMonth()]+', '+dateObj.getFullYear();
}
const ddate = new Date();
const result=formatDate(ddate)
document.getElementById("demo").innerHTML = result
<!DOCTYPE html>
<html>
<body>
<h2>Example:20th, Wednesday September, 2020 <h2>
<p id="demo"></p>
</body>
</html>
SaimumIslam27
  • 971
  • 1
  • 8
  • 14
0

I would suggest you to have a look into Moment.js if you have trouble with Angular. At least it is a quick workaround without spending too much time.

chunhoong
  • 105
  • 1
  • 10
0

Just use:

today:string = new Date().toJSON().slice(0,10).replace(/-/g,'/');
A.Casanova
  • 555
  • 4
  • 16