Why is the date in datepicker angular showing the last day?

前端 未结 6 691
深忆病人
深忆病人 2021-01-12 13:13

I use datepicker c angular material. Here\'s the code:


 
相关标签:
6条回答
  • 2021-01-12 13:18

    I solve this problem by converting datepicker date value to UTC. Here is example:

    const d = new Date(<DATE FROM FORM FIELD>);
    const date = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
    

    Maybe it's not elegant way to fix it but help me

    0 讨论(0)
  • 2021-01-12 13:25

    You may resolve it like this : For example, if your are getting date in -> one_day_back_date_value

    var one_day_back_date_value = moment.tz(moment(date_value_from_backend), 0).format("YYYY-MM-DD");
    date_value_from_backend = moment(one_day_back_date_value).toDate();
    

    Please note : moment and moment-timezone libraries are must for this. Include moment library above the moment-timezone library.

    0 讨论(0)
  • 2021-01-12 13:32

    I had a similar problem. I solved it by configuring Datepicker to use UTC dates. (It uses local time by default) Just add some providers on your component declaration :

    import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
    import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core';
    
    @Component({
      providers: [
        {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]},
        {provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true}}
      ]
    })
    
    0 讨论(0)
  • 2021-01-12 13:34

    Try this and it resolved the issue and there is nothing to do with the datepicker

    const d = new Date(fieldDate);
    d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
    console.log(d);
    
    0 讨论(0)
  • 2021-01-12 13:36

    Similar to the accepted answer, but a little less verbose and will keep the hours/minutes/seconds.

    const dt = new Date(event.value);
    const tz = dt.getTimezoneOffset();
    const seconds = (dt.getTime() / 1000) - (tz * 60);
    
    0 讨论(0)
  • 2021-01-12 13:39

    if you are not using moment or dont want to override complete date-datapter then you can override native-date-adapter

    @Injectable({        providedIn: 'root' }) 
    export class CustomDateAdapterService extends NativeDateAdapter {    
        public createDate(year: number, month: number, date: number): Date {
            const localDate = super.createDate(year, month, date);
            const offset = localDate.getTimezoneOffset() * 60000;
            return new Date(localDate.getTime() - offset); // utcDate
        } 
    }
    

    gist here

    0 讨论(0)
提交回复
热议问题