如何将日期转换为角度 2 中的“yyyy-MM-dd"格式 [英] How to convert date into this 'yyyy-MM-dd' format in angular 2

查看:8
本文介绍了如何将日期转换为角度 2 中的“yyyy-MM-dd"格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将当前数据转换成 .ts 文件中的 'yyyy-MM-dd' 格式.我的模板可以通过使用数据管道轻松完成.如何在打字稿中做到这一点.

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.

在模板中:

{{date  | date:'yyyy-MM-dd'}}

如何转换成这种格式'yyyy-MM-dd' in typescript.

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!

推荐答案

使用Datepipe可以将typescript中的日期转换成这种格式'yyyy-MM-dd'

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');
}

只需在 app.module.ts 的 'providers' 数组中添加 Datepipe.像这样:

and just add Datepipe in 'providers' array of app.module.ts. Like this:

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

这篇关于如何将日期转换为角度 2 中的“yyyy-MM-dd"格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆