在Angular 4中以'yyyy-MM-dd'格式获取当前日期 [英] get current date with 'yyyy-MM-dd' format in Angular 4

查看:133
本文介绍了在Angular 4中以'yyyy-MM-dd'格式获取当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何以特定格式'yyyy-MM-dd'来获取当前日期,以今天的i为例,结果为:'2018-07-12',仅使用命令即可

How i can get the current date with a specific format 'yyyy-MM-dd', for today by example i with that the result be: '2018-07-12', with using just the command

myDate = new Date();

非常感谢

推荐答案

您可以使用DatePipe在Angular中格式化日期.

You can use DatePipe for formatting Date in Angular.

在ts中,如果您要格式化日期,则可以像这样在构造函数中将DatePipe作为服务注入

In ts if you want to format date then you can inject DatePipe as Service in constructor like this

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

@Component({
    templateUrl: './name.component.html',
    styleUrls: ['./name.component.scss'],
    providers: [DatePipe]
})

myDate = new Date();
constructor(private datePipe: DatePipe){
    this.myDate = this.datePipe.transform(this.myDate, 'yyyy-MM-dd');
}

如果要在html文件中设置格式,"Shortdate"将返回MM/DD/YY类型的日期

And if you want to format in html file, 'Shortdate' will return date of type MM/DD/YY

{{myDate | date: 'shortDate' }}

从Angular 6开始,这也有效,

As of Angular 6, this also works,

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

formatDate(new Date(), 'yyyy/MM/dd', 'en');

这篇关于在Angular 4中以'yyyy-MM-dd'格式获取当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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