Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change date picker formcontrol value format with moment in angular material

I followed the example on material.angular.io for how to use moment with the material date picker and change the default format by providing MAT_DATE_FORMATS. The example is here. Note: the code doesn't work correctly in stackblitz, it seems to be ignoring the provided date formats but it does work correctly in my environment.

My issue is when I access the form control's value and convert it to JSON it always outputs "2018-01-16T15:44:33.897Z". I need it to output the date only "2018-01-16". Also I would prefer the date picker not add a time attribute at all. How can I make this work the way I want?

I know you can call moment's format function and get the date formatted any way you want but my form has many fields and I would prefer to just send form.value to my api. If I wanted to use moment's format function I would have to iterating over each control, check its type, get the value and format it individually, collect all the values into an object and then send it to my api which is a lot of extra coding just so I can format date controls.

like image 449
Curtis Avatar asked Nov 08 '22 11:11

Curtis


1 Answers

I ended up extending the moment object and overriding the toJSON method. I also copied and edited the MomementDateAdapter so it also used the edited version of moment and also created everything in UTC.

This is the moment override:

// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
import {default as _rollupMoment} from 'moment';
export class MomentConstructor
{
    static getInstance() {
        const original = _rollupMoment || _moment;
        original.prototype.toJSON = function() {
            return this.format("YYYY-MM-DD");
        }
        return original;
    }
}

//export the typing for Moment so it is easier to import into other classes
export interface Moment extends _moment.Moment {}

For the moment date adapter I found and copied the one provided by Material and edited it so that the moment import looked like this:

import { MomentConstructor, Moment } from './moment-date-only';
const moment = MomentConstructor.getInstance();

and I did a find replace on " moment(" and replaced it with " moment.utc(".

I built out an example on stackblitz but like I said in my question, stackblitz doesn't handle the adapter right so in order to see it working properly you need to implement it locally.

like image 61
Curtis Avatar answered Nov 14 '22 22:11

Curtis