5

I have used mat-datepicker for my Angular 6 project. But in date picker in is showing current timezone date. Instead of this I need to display current UTC date.

Here is my code

.ts file

var nowDate       =  new Date();
this.startdate    =  nowDate;
this.enddate      =  nowDate;

.html file

<mat-form-field style="margin-right: 25px;">
                    <input matInput [matDatepicker]="picker_start" placeholder="Start Date" [(ngModel)]="startdate" [ngModelOptions]="{timezone: 'UTC'}">
                    <mat-datepicker-toggle matSuffix [for]="picker_start"></mat-datepicker-toggle>
                    <mat-datepicker #picker_start></mat-datepicker>
                  </mat-form-field>
Yuri
  • 4,254
  • 1
  • 29
  • 46
Sandeep Nambiar
  • 1,656
  • 3
  • 22
  • 38

4 Answers4

23

You can use Moment.js with Material Datepicker and set the options accordingly like below :

import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';


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

I have created a sample on stackblitz. You can find out more at Choosing a date implementation and date format settings.

ThangLeQuoc
  • 2,272
  • 2
  • 19
  • 30
shhdharmen
  • 1,413
  • 10
  • 20
  • 1
    Moment.js will include all locales in the final build, can you please provide an alternate solution for this problem! – Bhargav Reddy Jan 23 '21 at 12:06
  • @BhargavReddy you can create your own date adapter in such case. Look at below answer. – shhdharmen Jan 25 '21 at 07:47
  • @shhdharmen hi i am using CUSTOM_DATE_FORMAT, how can we we get DatePicker date without timezone I need time "Sat Jan 08 2022 01:41:59 GMT+0500" without GMT +0500 any help will be apprcieated – khizer Jan 07 '22 at 20:42
3

I created my own Date Adapter as the example above didn't work for me. This also formats the date to a long format.

import { NativeDateAdapter } from '@angular/material';

export class AppDateAdapter extends NativeDateAdapter {

  format(date: Date, displayFormat: Object): string {
    return this.formateDate(date);
  }

  deserialize(value: any): Date | null {

    if ((typeof value === 'string') && (value.indexOf('-') > -1)) {
      const str = value.split('-');
      const dayArray = str[2].split('T');
      const year = Number(str[0]);
      const month = Number(str[1]) - 1;
      const day = Number(dayArray[0]);
      return new Date(Date.UTC(year, month, day));
    }

    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }

  createDate(year: number, month: number, date: number): Date {
    return new Date(Date.UTC(year, month, date));
  }

  parse(value: any): Date | null {
    if ((typeof value === 'string') && (value.indexOf('-') > -1)) {
      const str = value.split('-');
      const dayArray = str[2].split('T');

      const year = Number(str[0]);
      const month = Number(str[1]) - 1;
      const day = Number(dayArray[0]);

      return new Date(year, month, day);
    }

    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }

  formateDate(date: Date) {
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    return date.getDate() + '' + this.nth(date.getDate()) + ' ' + months[date.getMonth()] + ' ' + date.getFullYear();
  }

  nth(d: number) {
    if (d > 3 && d < 21) return 'th';
    switch (d % 10) {
      case 1: return 'st';
      case 2: return 'nd';
      case 3: return 'rd';
      default: return 'th';
    }
  }
}
CountZero
  • 6,171
  • 3
  • 46
  • 59
3

Provide this to use UTC

{provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } },

Provide This one for local support (FR for example)

{provide: MAT_DATE_LOCALE, useValue: 'fr-FR'},

The most important thing to make it works is to make DateAdapter depends on your defined settings.

{
  provide: DateAdapter,
  useClass: MomentDateAdapter,
  deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},

Full example of AppModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter } from '@angular/material-moment-adapter';

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
    ],
    providers: [
         {provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } },
         {provide: MAT_DATE_LOCALE, useValue: 'fr-FR'},
         {
             provide: DateAdapter,
             useClass: MomentDateAdapter,
             deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
         },
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}
Yacine MEDDAH
  • 1,211
  • 13
  • 17
0

You can extend DateFnsAdapter and override createDate

export class CustomDateAdapter extends DateFnsAdapter {


  constructor(
    @Inject(LOCALE_ID) public override locale:Locale
  ) {
    super(locale);
  }
  
  override createDate(year: number, month: number, date: number): Date{
    const tmpDate = new Date(0);
    tmpDate.setUTCFullYear(year)
    tmpDate.setUTCMonth(month)
    tmpDate.setUTCDate(date)
    return tmpDate
  } 

}
dsl400
  • 322
  • 3
  • 14