2

Looking to convert ISO date string on load in bootstrap/angular to 'MM/DD/YYYY'

Currently on load this is how the date picker looks: https://i.stack.imgur.com/g5MkI.jpg

We need the input date entered as 'MM/DD/YYYY' and then converted to ISO format

HTML

<form class="form-inline">
  <div class="form-group">
    <div class="input-group">
      <input class="form-control"
             name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker"
             [min]="minDate"
             [max]="maxDate"
             [style.width]="inputWidth"
             class="form-control"
      >
      <div class="input-group-append">
        <button class="btn btn-outline-secondary" (click)="d.toggle()" type="button">Pick Date
          <i class="fa fa-calendar"></i>
        </button>
      </div>
    </div>
  </div>
</form>
{{model.toISOString().substring(0,10)}}

TS

import {Component, Input} from '@angular/core';
import {NgbDateAdapter, NgbDateNativeAdapter} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'datepicker',
  templateUrl: './datepicker-popup.html',
  providers: [{provide: NgbDateAdapter, useClass: NgbDateNativeAdapter}]

})
export class NgbdDatepickerPopup {
  model: Date;
  @Input() disabled = false;
  @Input() required = false;
  @Input() displayValidation = false;
  @Input() minDate = null;
  @Input() maxDate = null;
  @Input() public inputWidth = '135px';
  dateInputMask = [/\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/];


  @Input() private format = 'YYYY-MM-DD';
  private inFormat = 'MM/DD/YYYY' || 'YYYY-MM-DD';
}

Currently the ISO format is working fine across the board but we need the user to be able to start with entering 'MM/DD/YYYY' format

ianhalfpenny
  • 147
  • 4
  • 15
  • Possible duplicate of [Converting a string to a date in JavaScript](https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript) – Heretic Monkey May 07 '19 at 21:10

2 Answers2

1

you can create a custom pipe that can transform into the format that you need

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
  transform(value: any, args?: any): any {
    return super.transform(value, 'mm/dd/yyyy');
  }
}

you html changes to

[ngModel]="model | dateFormat"

to convertback use a method to convert into ISOformat

(ngModelChange)="OnChange(event)"
Ashok
  • 743
  • 4
  • 13
  • SCRIPT5022: SCRIPT5022: Template parse errors: Parser Error: Cannot have a pipe in an action expression at column 9 in [model | dateFormat=$event] in ng:///NgbdDatepickerPopupModule/NgbdDatepickerPopup.html@4:23 (" div class="input-group"> input class="form-control" name="dp" [ERROR ->][(ngModel)]="model | dateFormat" ngbDatepicker #d="ngbDatepicker" [min]="minDate" "): ng:///NgbdDatepickerPopupModule/NgbdDatepickerPopup.html@4:23 – ianhalfpenny May 07 '19 at 21:31
  • can you remove (ngModelChange)="OnChange(event)" for now and let me know if it works – Ashok May 07 '19 at 21:38
1

The perfect solution would be to alter the file below, I have edited the code to get the required format(DD-MM-YYYY) in my input field.

ngb-date-parser-formatter.js

from the code below you will get DD-MM-YYYY Date format in input filed.

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
import { padNumber, toInteger, isNumber } from '../util/util';
/**
 * Abstract type serving as a DI token for the service parsing and formatting dates for the NgbInputDatepicker
 * directive. A default implementation using the ISO 8601 format is provided, but you can provide another implementation
 * to use an alternative format.
 */
var NgbDateParserFormatter = (function () {
    function NgbDateParserFormatter() {
    }
    return NgbDateParserFormatter;
}());
export { NgbDateParserFormatter };
var NgbDateISOParserFormatter = (function (_super) {
    __extends(NgbDateISOParserFormatter, _super);
    function NgbDateISOParserFormatter() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    NgbDateISOParserFormatter.prototype.parse = function (value) {
        if (value) {
            var dateParts = value.trim().split('-');
            if (dateParts.length === 1 && isNumber(dateParts[0])) {
                return { year: toInteger(dateParts[0]), month: null, day: null };
            }
            else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
                return { year: toInteger(dateParts[0]), month: toInteger(dateParts[1]), day: null };
            }
            else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
                return { year: toInteger(dateParts[0]), month: toInteger(dateParts[1]), day: toInteger(dateParts[2]) };
            }
        }
        return null;
    };

This is Where the date format is done

    NgbDateISOParserFormatter.prototype.format = function (date) {
        return date ?
        (isNumber(date.day) ? padNumber(date.day) : '')+"-"+ (isNumber(date.month) ? padNumber(date.month) : '') +"-"+ date.year:'';
    };


    return NgbDateISOParserFormatter;
}(NgbDateParserFormatter));
export { NgbDateISOParserFormatter };
//# sourceMappingURL=ngb-date-parser-formatter.js.map
Bharath Sagar
  • 52
  • 1
  • 7