Skip to content

Day incorrect in datepicker #7167

Description

@aceleghin

Bug, feature request, or proposal:

When I select a date I see the correct date in the field but, when I save, the datepicker send the day before the date I have selected

here's the code:
<md-form-field> <input mdInput [(ngModel)]="fareCalendar.startDate" name="startDate" [mdDatepicker]="picker" placeholder="startDate"> <md-datepicker-toggle mdSuffix [for]="picker"></md-datepicker-toggle> <md-datepicker #picker></md-datepicker> </md-form-field>

I am using angular 4 and @angular/material": "^2.0.0-beta.10
rtcnm

but the date:
f5z10

How can I send the UTC date

Activity

  1. julianobrasil commented on Sep 19, 2017

    @julianobrasil
    Contributor

    Could you try to reproduce it here, please: https://plnkr.co/edit/8nRKSJ?p=preview ?

  2. aceleghin commented on Sep 19, 2017

    @aceleghin
    Author

    I just want that the date I have selected in calendar is already in UTC timezone

  3. julianobrasil commented on Sep 19, 2017

    @julianobrasil
    Contributor

    That's why I'm asking you to reproduce it in the plunk. For me it's working fine, but it's possible that some bug is happening in your case:

    image

    If it's just a matter of configs, stackovervlow.com is more suitable than this channel.

  4. julianobrasil commented on Sep 19, 2017

    @julianobrasil
    Contributor

    The calendar returns a javascript Date object. What you've shown in above message seems like something generated from other source (it looks like a JSON.stringify() result or maybe from a database service). To get back the Javascript Date object, you have to do (really not sure how did you get that result):

    fareCalendar.startDate = new Date(fareCalendar.startDate);
  5. aceleghin commented on Sep 19, 2017

    @aceleghin
    Author

    If I select th date: 6/9/2017 and print it I see:
    Wed Sep 06 2017 00:00:00 GMT+0200

    Then I save the date in a body const body = { startDate: this.fareCalendar.startDate };
    And make post request.
    I am using Http client

  6. julianobrasil commented on Sep 19, 2017

    @julianobrasil
    Contributor

    Oh, you may be refering to the fact that the UTC time add/subtract your current time offset. Look at the picture below: I'm in a GMT+2h00 zone, so, my UTC value is offset by 2 hours. So, if I set the hours to 23h00 in my Date object, my UTC date get offset to the day after (as in 1h00 am).

    image

  7. aceleghin commented on Sep 19, 2017

    @aceleghin
    Author

    Yes, I want the date selected is already UTC, I used primeng calendar and there is a property like utc="true" that solve this.
    If I select 22/9/2017 I want send: 2017-09-22T00:00:00.000Z

  8. julianobrasil commented on Sep 19, 2017

    @julianobrasil
    Contributor

    Well... I really don't know if it's planned to support such a utc attribute.

    cc: @mmalerba

  9. mmalerba commented on Sep 19, 2017

    @mmalerba
    Contributor

    We do plan to add support for different timezones/offsets, but its not there yet. In the mean time you could make a custom DateAdapter that works with UTC dates to accomplish this.

    Here is the DateAdapter class you would have to extend:
    https://github.com/angular/material2/blob/master/src/lib/core/datetime/date-adapter.ts

    Some examples of existing implementations:
    https://github.com/angular/material2/blob/master/src/lib/core/datetime/native-date-adapter.ts
    https://github.com/angular/material2/blob/master/src/material-moment-adapter/adapter/moment-date-adapter.ts

    And some documentation that may help:
    https://material.angular.io/components/datepicker/overview
    https://blog.angular.io/taking-advantage-of-the-angular-material-datepicker-237e80fa14b3

  10. we125182 commented on Sep 21, 2017

    @we125182

    @lippomano I have the same request. Did you get any solution about it ? thank you for any suggestions.

  11. aceleghin commented on Sep 28, 2017

    @aceleghin
    Author

    @we125182 I write a method that manipulate every date it is not the best practice but it's simpler for me

  12. adaojunior commented on Oct 3, 2017

    @adaojunior

    I'm also getting a incorrect date.

    bug-on-datetime

  13. adaojunior commented on Oct 3, 2017

    @adaojunior

    I get this exact same behaviour on https://material.angular.io/components/datepicker/overview
    It always adds +1 day after selected.

  14. mmalerba commented on Oct 3, 2017

    @mmalerba
    Contributor

    @adaojunior if you're seeing the same issue on the docs site its likely some issue related to your locale / time zone. Any additional information you can provide would be useful. If you're using Moment.js in your app (or willing to try it) you could give the MomentDateAdapter a try and see if it resolves your issue. Just add the MatMomentDateModule from @angular/material-moment-adapter at your application root instead of MatNativeDateModule

  15. 23 remaining items

  16. Silthus commented on May 15, 2018

    @Silthus
    Contributor

    @mmalerba I can send a PR later this day.

  17. added a commit that references this issue on May 15, 2018
    1db44c3
  18. added 2 commits that reference this issue on Jun 5, 2018
    1577506
    d0abfc9
  19. glucena commented on Jul 3, 2018

    @glucena

    You can change the default behaviour to parse dates as UTC by providing the MAT_MOMENT_DATA_ADAPTER_OPTIONS and setting it to useUtc: true.

    @NgModule({
    imports: [MatDatepickerModule, MatMomentDateModule],
    providers: [
    { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
    ]
    })

    Check here for more details

  20. smnbbrv commented on Aug 22, 2018

    @smnbbrv

    MAT_MOMENT_DATE_ADAPTER_OPTIONS - oh man, that's so awesome!

    However, this..., it's not should, it must be default configuration for datepicker.

  21. raibait commented on Oct 1, 2018

    @raibait

    Why does datepicker care about the timezones at all? Who would ever need that?

  22. julianobrasil commented on Oct 1, 2018

    @julianobrasil
    Contributor

    @raibait, in fact, it doesn't care about it. But the underlying objects that currently store the date values usually do (regular javascript Date objects and Moment.js are the most common cases). This is the reason for so many issues related to wrong dates. Building a date adapter and configuring it correctly is important to avoid headaches.

  23. thw0rted commented on Nov 26, 2018

    @thw0rted

    Maybe the problem here is the fact that the datepicker's value is a Date in the first place. Date is a perfectly good(ish) class for representing an absolute instant in real time; it's a terrible representation of a calendar date. This entire thread, dozens of posts, dozens of users complaining, could have been avoided if the default date adapter went to/from ISO 8601 date-only strings. Every date library (and of course the native Date object) understands them, they are exactly as specific as the UI that generated them, and they can be "upgraded" to an instant or range of real time by simply adding "Z" on the end. What I mean to say is, adding context to go from "2018/11/26" to "2018/11/26Z" makes sense, but going the other way -- trying to remove time-zone-ness from the data -- does not.

    Of course, I can fix all this by writing my own date adapter, or going out and getting the Moment-based one, but as long as the default behavior is Date-based, you're going to keep seeing people showing up in this thread.

  24. nugrohotanjo commented on Apr 20, 2019

    @nugrohotanjo

    I made my self a workaround by overriding the MomentJS DateAdapter compiling the date from UTC and then converting it into the locale date:

    import { Inject, Injectable, Optional } from '@angular/core';
    import { MAT_DATE_LOCALE } from '@angular/material';
    import { MomentDateAdapter } from '@angular/material-moment-adapter';
    import { Moment } from 'moment';
    import * as moment from 'moment';
    
    @Injectable()
    export class MomentUtcDateAdapter extends MomentDateAdapter {
    
      constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) {
        super(dateLocale);
      }
    
      createDate(year: number, month: number, date: number): Moment {
        // Moment.js will create an invalid date if any of the components are out of bounds, but we
        // explicitly check each case so we can throw more descriptive errors.
        if (month < 0 || month > 11) {
          throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`);
        }
    
        if (date < 1) {
          throw Error(`Invalid date "${date}". Date has to be greater than 0.`);
        }
    
        let result = moment.utc({ year, month, date }).locale(this.locale);
    
        // If the result isn't valid, the date must have been out of bounds for this month.
        if (!result.isValid()) {
          throw Error(`Invalid date "${date}" for month with index "${month}".`);
        }
    
        return result;
      }
    }
    

    The important line being:

    let result = moment.utc({ year, month, date }).locale(this.locale);
    

    thanks, it's work very well :)

  25. Achyuthkodali commented on Jul 15, 2019

    @Achyuthkodali

    @Silthus the adapter you did works like a charm, but I have a requirement to set the format for the date.
    How can I achieve that alongside timezone adapter?

    my date format: "DD MMM YYYY" // 15 jul 2019

  26. christrude commented on Sep 9, 2019

    @christrude

    I am wondering if adding the useUTC portion to a component's providers instead of the module's providers will not work?

    When using the Honolulu timezone (spoofing the browser), we were not able to make moment work, we ended up having to manually remove the timezone offset in order to get the mat-datepicker to choose the correct date:

    let newDate= new Date(initialInfo.value); newDate.setMinutes(newDate.getMinutes() + newDate.getTimezoneOffset()); variableValueCtrl.reset(newDate);

    When I tried to get it to work with moment it cause a whole host of other issues. However this still causes the selection to be wrong:

    Screen Shot 2019-09-09 at 2 10 57 PM

    Not looking for a solution, just alerting to the issues

  27. christrude commented on Sep 9, 2019

    @christrude

    Stackblitz showing crazy go nuts wonky-ness when you have your browser spoofed to India time:

    https://stackblitz.com/edit/angular-trude-datetest

    Screen Shot 2019-09-06 at 5 32 37 PM

    And in that stack blitz, look at what it selects in the UI:

    Screen Shot 2019-09-09 at 2 42 41 PM

    So set to the 6th, moment converts to the 5th, mat-datepicker displays the 4th, but selects the 3rd.

  28. angular-automatic-lock-bot commented on Oct 10, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  29. locked and limited conversation to collaborators on Oct 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions