Search code examples
angularngx-bootstrap

Incorrect Date when changing month


I have integrated BsDatepickerModule from ngx-bootstrap in my app module to let user filter a list by date. The problem is when I change month(for example moving from january to february, I'm getting incorrect date(day - 1).

Here is the app module:

@NgModule({
    declarations: [AppComponent],
    imports: [BsDatepickerModule.forRoot() ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Here is the component:

onValueChange(value: Date): void {
    console.log(value.toISOString().split('T')[0]);
});

When I change the month and then select for example 2019/01/07 the output print 2019/01/06

What is wrong ?

Notice that I'm converting the date to get it in format YYYY-mm-dd


Solution

  • It is written in the MDN docs that, monthIndex is 0 based.

    So to convert month from Date constructor to human readable month, add 1 to the value.

    new Date().getMonth() + 1

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth

    Edit:

    Ok I have created a stackblitz demo. Check and see if you want your app to be like this.

    https://stackblitz.com/edit/angular-z3vtli

    Edit 2:

    I have updated the demo. You should not be converting date to toISOString() as it is by default (I think). Go for toLocalDateString() if you want the same as your local date.

    Credits:

    One of my seniors at work.

    @Eliseo (In the comments section)