Convert string to date using moment.js
本问题已经有最佳答案,请猛点这里访问。
这是我的模型。ts
1 2 3 4 5 6 7 8 9 10 11 | export class Feature2 { requestRouteTemplate: string; requestMethod: string; numberCount: number; requestDate: date; constructor(values: Object = {}) { Object.assign(this, values); } } |
这是component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 | this.datas2 = [ { 'requestRouteTemplate': 'api/Tasks', 'requestMethod': 'POST', 'numberCount': 6, 'requestDate': '07/01/2017', }, { 'requestRouteTemplate': 'api/Tasks', 'requestMethod': 'POST', 'numberCount': 3, 'requestDate': '07/02/2017', }, |
我想使用矩型库将请求日期变量从字符串转换为日期。
在构造函数中添加:
请参阅文档:
- https://momentjs.com/docs/#/parsing/string-format/
- https://momentjs.com/docs/#/displaying/as-javascript-date/
您必须创建如下所示的管道
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //datePipe.ts import { Pipe, PipeTransform } from '@angular/core'; import moment from 'moment'; @Pipe({ name: 'datex' }) export class DatexPipe implements PipeTransform { transform(value: any, format: string =""): string { // Try and parse the passed value. var momentDate = moment(value); // If moment didn't understand the value, return it unformatted. if (!momentDate.isValid()) return value; // Otherwise, return the date formatted as requested. return momentDate.format(format); } } |
,然后您可以在html页面
中使用它
1 | {{datas2.requestDate | datex:'YYYY-MM-DD HH:mm'}} |