6

I need to display dates in two different formats based on some user settings.

Let's say "YYYY-MM-DD" and "DD/MM/YYYY".

I know that I have to write a custom DateAdapter (I've already done that), but is it possible to switch between the two formats with e.g. a dropdown list?

P.S. I'm also using Moment.js.

2 Answers 2

6

Your custom date format is in a TS file.

This means you have access to Javascript and Typescript.

What you could do is use the localStorage to store the format, and in your date format :

export const CUSTOM_DATE_FORMAT = {
  parse: {
    dateInput: localStorage.getItem('dateFormat'),
  },
  display: {
    dateInput: localStorage.getItem('dateFormat'),
    monthYearLabel: 'MMMM YYYY',
    dateA11yLabel: 'DD/MM/YYYY',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

I think you'll figure out how to store the formatin the local storage ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works! Have you got maybe an idea, how to do it without reloading the window? If no, I'll accept this answer as it definitely works.
To avoid reloading the window, you would need to rewrite the module where you declare your custom date adapter. I don't know how to do that, sorry :/
2

Below you can see a custom adpater using the local storage. In this way, you don't have to reload the window.

import { MomentDateAdapter, MatMomentDateAdapterOptions } from "@angular/material-moment-adapter";
import { Moment } from "moment";
import { UserService } from "app/core/api/user.service";

export class CustomDateAdapter extends MomentDateAdapter {

    parse(value: any, parseFormat: string | string[]): Moment | null {
        let dateFormat: string | string[] = localStorage.getItem("dateFormat") || parseFormat;
        return super.parse(value, dateFormat);
    }

    format(date: Moment, displayFormat: string): string {
        let dateFormat: string | string[] = localStorage.getItem("dateFormat") || displayFormat;
        return super.format(date, dateFormat);
    }

}

And in your module:

....
import { MAT_DATE_FORMATS } from '@angular/material/core';
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS } from '@angular/material-moment-adapter';
import { CustomDateAdapter } from 'app/material/custom-date-adapter';

....
providers: [
    { provide: DateAdapter, useClass: CustomDateAdapter },
    { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } },
    { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
]})
export class MaterialModule { }

Please notice that this example uses the momentjs implementation of the DateAdapter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.