0

I am using Angular 5 for my project.So I have date input field in form for this I am using NgbDatepicker but I am unable to set the yyyy-mm-dd format.And also when I am selecting date , it is showing One day before date.Please help me out.

<form class="form-inline">
    <div class="form-group">
      <div class="input-group">
        <input class="form-control" placeholder="yyyy-mm-dd"
               name="d2" #c2="ngModel" [(ngModel)]="model2" ngbDatepicker #d2="ngbDatepicker">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary" (click)="d2.toggle()" type="button">
            calender
          </button>
        </div>
      </div>
    </div>
  </form>
  <hr/>
  <pre>Model: {{ model2 | json }}</pre>

app.component.ts

import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
model2: Date;
}

output: Model: "2018-01-31T18:30:00.000Z" , here I have selected 2018-02-01

Urvashi Urvi
  • 11
  • 2
  • 7

1 Answers1

2

Are you use the https://ng-bootstrap.github.io/#/components/datepicker/examples ? or an old version?

If you're using the ng-bootstrap, I must supouse that you're using a datepicker-adapter (ngbDatepicker, by defect are feeding by ngDateStructure) The problem is that the example is wrong

//This function it's not correct
toModel(date: NgbDateStruct): Date {
    return date ? new Date(date.year, date.month - 1, date.day) : null;
  }
//Change by 
toModel(date: NgbDateStruct): Date {
    return date ? new Date(''+date.year+'-'+date.month+'-'+date.day) : null;
  }

The problem is that new Date() take account the GTM Zone, so if you live in a GTM +, the first function give you a day less

About the dateFormat, you have a NgbDateParserFormatter. Check it

Eliseo
  • 50,109
  • 4
  • 29
  • 67