如何在Typscript中将日期格式化为所需日期
问题描述:
我有一个日期字符串,如2016-09-19T18:10:31 + 0100。我在做如何在Typscript中将日期格式化为所需日期
let dateString:string = 2016-09-19T18:10:31+0100;
let newDateString:Date = new Date(dateString);
而且我得到的输出作为星期二2016年9月19日18时十分31秒GMT + 0530(印度标准时间)。但我希望日期格式为19.9.2016 18:10
如何将其格式化为具有所需的格式?
答
您可以使用DatePipe在HTML模板像这个 -
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template:`<h1>My First Angular 2 App</h1>
<p>{{newDateString | date: 'dd.MM.yyyy hh:mm'}} - format: dd.MM.yyyy hh:mm</p>`
})
export class AppComponent {
dateString: string = "2016-09-19T18:10:31+0100";
newDateString:Date = new Date(this.dateString);
}
DatePipe文档:https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html#!#sts=Pipe
UPDATE:
如果你只是想格式化的日期时间打字稿(没有angular2),那么你可以尝试像这样 -
options = { year: 'numeric', month: 'numeric', day: 'numeric', hour:'numeric', minute: 'numeric', hour12: false };
displayDate = new Date().toLocaleDateString(undefined, this.options);
在2号线,而不是undefined
可以传递locales
值喜欢这个 - “EN-US”,“EN-GB”等
我不能使用,因为我格式化HTML日期使用第三方模块(Ag Grid),所以我需要提供格式化日期到HTML –