How to convert date into this 'yyyy-MM-dd'

2019-02-02 00:56发布

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!

4条回答
Viruses.
2楼-- · 2019-02-02 01:32

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.

查看更多
叼着烟拽天下
3楼-- · 2019-02-02 01:35

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.

查看更多
来,给爷笑一个
4楼-- · 2019-02-02 01:46

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]
查看更多
5楼-- · 2019-02-02 01:53

A simple solution would be to just write

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

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

Hope this helps.

查看更多
登录 后发表回答