简体   繁体   中英

How to set default format as ('dd/mm/yyyy') in ng-bootstrap

https://puu.sh/yThgV/bd55df9829.png

html

<label for="date">{{ "date" | translate }}</label>
<input type="date" class="form-control checking-field" id="date">

I want to get that format ('dd/mm/yyyy') . Any Suggestion?

extends my comment

In your app.module

import { NgbDatepickerConfig, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
import { NgbDateFRParserFormatter } from "./ngb-date-fr-parser-formatter"

@Component({
    providers: [{provide: NgbDateParserFormatter, useClass: NgbDateFRParserFormatter}]
})
export class AppComponent {}

In your NgbDateFRParserFormater

//your NgbDateFRParserFormater extends from NgbDateParserFormatter
//Is a Injectable that have two functions
@Injectable()
export class NgbDateFRParserFormatter extends NgbDateParserFormatter {
    parse(value: string): NgbDateStruct { //parse receive your string dd/mm/yyy
         //return a NgbDateStruct
         //calculate year,month and day from "value"
        return {year:year,month:month,day:day}
    }

    format(date: NgbDateStruct): string { //receive a NgbDateStruct
        //return a string
        return ''+date.day+'/'+date.month+'/'+date.year;
    }
}

My complete working solution:

Create a folder named "date-picker" and add the following files inside it.

date-picker > ngb-date-parser-formatter-ext.service.ts

date-picker > index.ts

The file

date-picker > ngb-date-parser-formatter-ext.service.ts

import { NgbDateParserFormatter, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";

import { Injectable } from "@angular/core";

@Injectable()
export class NgbDateParserFormatterExtService extends NgbDateParserFormatter {
private dateSeparatorChar: string = "-";

// dateFormat should be "yyyy-MM-dd" or "dd-MM-yyyy" with the valid separator.
private dateFormat = `yyyy${this.dateSeparatorChar}MM${this.dateSeparatorChar}dd`;

parse(value: string): NgbDateStruct {
 if (value === "") {
   return null;
 }

 const dateString: string = value;
 const dateValues = dateString.split(this.dateSeparatorChar);

 if (dateValues.length !== 3) {
   return null;
 }

 let dayIndex: number;
 let yearIndex: number;

 if (this.dateFormat === "dd-MM-yyyy") {
   dayIndex = 0;
   yearIndex = 2;
 } else {
   dayIndex = 2;
   yearIndex = 0;
 }

 const year = Number(dateValues[yearIndex]);
 const month = Number(dateValues[1]);
 const day = Number(dateValues[dayIndex]);

 const date: NgbDateStruct = {
   year: year, month: month, day: day
 };

 return date;
}

format(date: NgbDateStruct): string {
 if (date === null) {
   return "";
 }

 const dayString: string = date.day < 10 ? `0${date.day}` : `${date.day}`;
 const monthString: string = date.month < 10 ? `0${date.month}` : `${date.month}`;
 const separator = this.dateSeparatorChar;

 const dateString = this.dateFormat === "dd-MM-yyyy"
   ? `${dayString}${separator}${monthString}${separator}${date.year}`
   : `${date.year}${separator}${monthString}${separator}${dayString}`;

 return dateString;
 }
}

The file

date-picker > index.ts

import { NgbDateParserFormatter } from "@ng-bootstrap/ng-bootstrap";
import { NgbDateParserFormatterExtService } from "./ngb-date-parser-formatter-ext.service";

export const NgbDateParserFormatterExtProvider =
  { provide: NgbDateParserFormatter, useClass: NgbDateParserFormatterExtService };

In the file

app.module.ts

import { NgbDateParserFormatterExtProvider } from "./common/services/date-picker";

@NgModule({

  providers: [...., NgbDateParserFormatterExtProvider],

})
export class AppModule { }

In your

your-component1.component.html

 <div class="form-group">
    <label>Publish Date</label><span> * </span>
    <input #datepicker="ngbDatepicker" class="form-control" name="datepicker" formControlName="publishDate"
      ngbDatepicker (click)="datepicker.toggle()" placeholder="yyyy-MM-dd" />
  </div>

I'm using Reactive forms.

You can change the date format to "dd-MM-yyyy" or "dd/MM/yyyy" by setting the variable

private dateFormat = `yyyy${this.dateSeparatorChar}MM${this.dateSeparatorChar}dd`;

Regards..

In general you need to use directive.

So, you can use one of ready-made date-time pickers for angular. Like this: https://www.npmjs.com/package/angular-date-time-input

Or create your own directive to make it work.

myModule.directive(
'dateInput',
function(dateFilter) {
    return {
        require: 'ngModel',
        template: '<input type="date"></input>',
        replace: true,
        link: function(scope, elm, attrs, ngModelCtrl) {
            ngModelCtrl.$formatters.unshift(function (modelValue) {
                return dateFilter(modelValue, 'yyyy-MM-dd');
            });

            ngModelCtrl.$parsers.unshift(function(viewValue) {
                return new Date(viewValue);
            });
        },
    };
});

I took this code from: https://stackoverflow.com/a/18062552/3710672

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM