Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 datepicker locale not working properly

I'm using ng-pick-datetime UI component for the date picker. I disabled readonly mode, so that the input is active for typing with keyboard.

<owl-date-time name="client_birthday" #client_birthday="ngModel"
    [placeHolder]="'DD.MM.YYYY'"
    [locale]="ru"
    [(ngModel)]="client.client_birthday"
    [type]="'calendar'"
    [dataType]="'string'"
    [dateFormat]="'DD.MM.YYYY'"
    [readonlyInput] ="false"
    [autoClose] ="true"
    [inputId]="'client_birthday'"                                                   
></owl-date-time>

I try to apply RU locale using date-fns:

ru: any;
ruLocale = require('date-fns/locale/ru');
ngOnInit() {     
    this.ru = {
        firstDayOfWeek: 1,
        dayNames: [...],
        dayNamesShort: [...],
        monthNames: [...],
        monthNamesShort: [...],
        dateFns: this.ruLocale
    };
}

When I type into the input with dd.mm.yyyy format, the picker makes day as a month and month as a day, and the year is ok. So, the only format it recognizes is mm.dd.yyyy, which seems to be us locale. My calendar language changed as expected, but is it possible to configure date format for RU as well?

I would appreciate any help.

like image 635
Gyuzal R Avatar asked Nov 20 '17 06:11

Gyuzal R


2 Answers

It seams unable to do what you want when input date by typing on input box of ng-pick-datetime. I went through the implementation of the ng-pick-datetime Component. When typing, given input converting to date object by using https://date-fns.org/v1.29.0/docs/parse Here is the implementation picker.component.ts/src/picker.component.ts Line-1177 Method-parseToDate

/**
     * Parse a object to Date object
     * @param {any} val
     * @return {Date}
     * */
    private parseToDate( val: any ): Date {
        if (!val) {
            return;
        }

        let parsedVal;
        if (typeof val === 'string') {
            parsedVal = parse(val, this.dateFormat, this.now);
        } else {
            parsedVal = val;
        }

        return isValid(parsedVal) ? parsedVal : null;
    }

https://github.com/DanielYKPan/date-time-picker has used "date-fns": "^2.0.0-alpha.7g" on package json. It has a argument to pass the date format to parse date.

parsedVal = parse(val, this.dateFormat, this.now);

But latest version of date-fns: "^1.29.0", Do not have parmeter to pass the date format. So it fails on your project too. Please read https://date-fns.org/v1.29.0/docs/parse

parse(argument, [options])
like image 152
Janith Widarshana Avatar answered Sep 21 '22 22:09

Janith Widarshana


similar to this:

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "ru-ru"},
    //otherProviders...
  ]
})

have a look at this How to set locale in DatePipe in Angular 2?

like image 43
sancelot Avatar answered Sep 21 '22 22:09

sancelot