问题
This my model.ts
export class Feature2 {
requestRouteTemplate: string;
requestMethod: string;
numberCount: number;
requestDate: date;
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
This is component.ts
this.datas2 = [
{
'requestRouteTemplate': 'api/Tasks',
'requestMethod': 'POST',
'numberCount': 6,
'requestDate': '07/01/2017',
},
{
'requestRouteTemplate': 'api/Tasks',
'requestMethod': 'POST',
'numberCount': 3,
'requestDate': '07/02/2017',
},
I want to convert the request date variable from string to date using the moment library.
回答1:
In your constructor add: this.requestDate = moment(values.requestDate, "MM-DD-YYYY").toDate();
See the documentation:
- https://momentjs.com/docs/#/parsing/string-format/
- https://momentjs.com/docs/#/displaying/as-javascript-date/
回答2:
You have to create pipe like below
//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);
}
}
and then you can use it in html page
{{datas2.requestDate | datex:'YYYY-MM-DD HH:mm'}}
来源:https://stackoverflow.com/questions/45029300/convert-string-to-date-using-moment-js