Преобразуйте строку в дату с помощью moment.js

Это моя модель.

 export class Feature2 {

 requestRouteTemplate: string;
 requestMethod: string;
 numberCount: number;
 requestDate: date;

 constructor(values: Object = {}) {
  Object.assign(this, values);  
 }
}

Это 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',
  },

Я хочу преобразовать переменную даты запроса из строки в дату, используя библиотеку моментов.


person Deniz Adıbelli    schedule 11.07.2017    source источник


Ответы (2)


В вашем конструкторе добавьте: this.requestDate = moment(values.requestDate, "MM-DD-YYYY").toDate();

См. Документацию:

person DDeis    schedule 11.07.2017

Вы должны создать трубу, как показано ниже

//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

{{datas2.requestDate | datex:'YYYY-MM-DD HH:mm'}}
person Trusha    schedule 11.07.2017