Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - MdDatepickerModule - European format

I use MdDatePickerModule to pick dates but I have a problem: If I select August 5, everything is ok. But if I reopen the selection the month changes and becomes May, if I select May 3, I close, re-open, the month is March. Now I know that the problem is that in America the month and the day are inverted compared to Europe, but what is the "smart" way to resolve the conflict. thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct way of doing it for now is to set the locale as well as having a custom adapter to parse the date properly.

ts:

import {Component} from '@angular/core';
import { NativeDateAdapter, DateAdapter, MD_DATE_FORMATS } from "@angular/material";

export class ItalianDateAdapter extends NativeDateAdapter {
  parse(value: any): Date | null {
    if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
      const str = value.split('/');
      if (str.length < 2 || isNaN(+str[0]) || isNaN(+str[1]) || isNaN(+str[2])) {
        return null;
      }
      return new Date(Number(str[2]), Number(str[1]) - 1, Number(str[0]), 12);
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }
}

@Component({
  selector: 'datepicker-overview-example',
  templateUrl: './datepicker-overview-example.html',
  styleUrls: ['./datepicker-overview-example.css'],
  providers: [{provide: DateAdapter, useClass: ItalianDateAdapter}],
})
export class DatepickerOverviewExample {

  locale: string;

  constructor(private dateAdapter: DateAdapter<Date>) {
    this.locale = 'it';
    this.dateAdapter.setLocale('it');   
  }

}

Plunker demo

This bug has been reported to Material team and being tracked by the following issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...