Convert string to date using moment.js [duplicate]

一世执手 提交于 2021-01-29 06:45:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!