我该如何使用特定格式'yyyy-MM-dd'获取当前日期,例如今天的日期是'2018-07-12'?仅使用一条命令即可实现。
myDate = new Date();
非常感谢
myDate = new Date();
非常感谢
你可以在Angular中使用DatePipe来格式化日期。
如果你想要在ts中格式化日期,那么你可以像这样在构造函数中注入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 文件中进行格式化,"Shortdate" 将返回 MM/DD/YY 类型的日期。
{{myDate | date: 'shortDate' }}
从Angular 6开始,这也可以正常工作。
import {formatDate} from '@angular/common';
formatDate(new Date(), 'yyyy/MM/dd', 'en');
你可以尝试这样做。
component.ts
currentDate = new Date();
组件.html
{{currentDate | date:'yyyy-MM-dd'}}
date:'yyyy-MM-dd'
管道。curDate=new Date();
<p>{{curDate | date:'yyyy-MM-dd'}}</p>
仅日期:
your date | date: 'dd MMM yyyy'
日期和时间:
your date | date: 'dd MMM yyyy hh:mm a'
如果您只想从 new Date() 提取日期输入,则可以像这样在 ts 文件中使用 angular formatDate():
currentDate = new Date();
const cValue = formatDate(currentDate, 'yyyy-MM-dd', 'en-US');
以下是示例:
function MethodName($scope)
{
$scope.date = new Date();
}
<div ng-app ng-controller="MethodName">
My current date is {{date | date:'yyyy-MM-dd'}} .
</div>
app.component.html
<div>
<h5 style="color:#ffffff;">{{myDate | date:'fullDate'}}</h5>
</div>
app.component.ts
export class AppComponent implements OnInit {
myDate = Date.now(); //date
In Controller ,
var DateObj = new Date();
$scope.YourParam = DateObj.getFullYear() + '-' + ('0' + (DateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + DateObj.getDate()).slice(-2);
<input type="datetime-local">
一起使用,例如:
<input matInput #dateTimeInput type="datetime-local" [value]="todayAsString" step="1" [min]="todayAsString">
那么应该将 todayAsString
设置为:this.todayAsString = formatDate(new Date(), 'yyyy-MM-dd', 'en');
this.todayAsString += 'T' + formatDate(new Date(), 'hh:mm', 'en');
文档:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input/datetime-local
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-name-class',
templateUrl: './name.component.html',
styleUrls: ['./name.component.scss']
})
export class NameComponent implements OnInit {
// define datepipe
datePipe: DatePipe = new DatePipe('en-US');
constructor(){}
// method to get formatted date
getformattedDate(){
var date = new Date();
var transformDate = this.datePipe.transform(date, 'yyyy-MM-dd');
return transformDate;
}
}