在Angular 4中以'yyyy-MM-dd'格式获取当前日期

问题描述 投票:8回答:5

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

myDate = new Date();

非常感谢

angular
5个回答
22
投票

您可以使用DatePipe格式化Angular中的日期。

如果你想格式化日期,那么你可以像这样在构造函数中注入DatePipe作为服务

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文件,

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

从Angular 6开始,这也有效,

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

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

4
投票

这是一个例子:

function MethodName($scope)
{
    $scope.date = new Date();
}

你可以在这里更改格式,我们有一个代码

<div ng-app ng-controller="MethodName">
    My current date is {{date | date:'yyyy-MM-dd'}} . 
</div>

我希望它有所帮助。


3
投票

你可以使用date:'yyyy-MM-dd'管道

curDate=new Date();

<p>{{curDate | date:'yyyy-MM-dd'}}</p>

1
投票

在控制器中,

 var DateObj = new Date();

 $scope.YourParam = DateObj.getFullYear() + '-' + ('0' + (DateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + DateObj.getDate()).slice(-2);

1
投票

你可以尝试这样做。


component.ts

currentDate = new Date();

component.html

{{currentDate | date:'yyyy-MM-dd'}}
© www.soinside.com 2019 - 2024. All rights reserved.