如何解决日期时间选择器本地化问题

时间:2020-02-18 09:40:02

标签: html angular date datepicker

我对日期有疑问,例如,如果输入日期 2020年2月18日,则数据库中保存的日期为 2020年2月17日22:00 :00 !!! 通常是时区问题吗?如何解决这个问题,谢谢。如果我想用UTC保存日期,该怎么做?

code .html:

<ng-template #datepicker>
  <label title="{{cell.about}}" class="col-lg-5 col-md-5 col-sm-5 col-xs-5 " style="margin-top: 5px;">{{cell.label}} <span class="br-required-star" *ngIf="cell.required">*</span></label>
  <div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 " style="padding: 0px;">
    <ng-container *ngIf="cell.type === 'date';else select2">
      <mat-form-field class="date-Picker-br-object">
        <input [disabled]="!cell.editable" name="{{cell.id}}" [required]="cell.required" style="width: 100% !important;" matInput [matDatepicker]="i" [(ngModel)]="cell.value" [disabled]="!cell.editable">
        <mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle>
        <mat-datepicker #i></mat-datepicker>
      </mat-form-field>
    </ng-container>
    <div *ngIf="brDetailsForm.controls[i] && !brDetailsForm.controls[i].valid && !brDetailsForm.controls[i].pristine" class="alert alert-danger errorMessage">{{msgRequired(cell.label)}}</div>
    <div *ngIf="otherErrorMessages && otherErrorMessages[i]" class="alert alert-danger errorMessage">{{otherErrorMessages[i]}}</div>
  </div>
</ng-template>

2 个答案:

答案 0 :(得分:0)

您可以将Moment.js与Material Datepicker一起使用,并相应地设置以下选项

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

您可以在以下位置找到更多信息: https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings

答案 1 :(得分:0)

我解决了问题,创建了一个名为format-datepicker的组件。
format-datepicker.ts:

import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from "@angular/material";
import * as moment from 'moment';

export class AppDateAdapter extends NativeDateAdapter {

    parse(value: any): Date | null {
        if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
          const str = value.split('/');
          const year = Number(str[2]);
          const month = Number(str[1]) - 1;
          const date = Number(str[0]);
          return new Date(Date.UTC(year, month, date));
        }
        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));
      }

      format(date: Date, displayFormat: Object): string {
        let now = moment();
        if (displayFormat === 'input') {
          let day: string = date.getUTCDate().toString();
          day = +day < 10 ? '0' + day : day;
          let month: string = (date.getUTCMonth() + 1).toString();
          month = +month < 10 ? '0' + month : month;
          let year = date.getUTCFullYear();
          return `${day}/${month}/${year}`;

        }
        // new Date(date.toDateString()).getUTCDate(); 
        return date.toDateString();

      }

   private _to2digit(n: number) {
       return (n);
       //return ('00' + n).slice(-2);
   } 
}

export const APP_DATE_FORMATS =
{
   parse: {
       dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
   },
   display: {
       // dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
       dateInput: 'input',
       // monthYearLabel: { month: 'short', year: 'numeric', day: 'numeric' },
       monthYearLabel: 'inputMonth',
       dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
       monthYearA11yLabel: {year: 'numeric', month: 'long'},
   }
}

format-datepicker.html:

<mat-form-field>
  <input matInput placeholder="Select Date" [matDatepicker]="datepickerRef" name="datepicker" ngModel #dateCtrl="ngModel" required readonly/>
  <mat-datepicker-toggle [for]="datepickerRef" matSuffix></mat-datepicker-toggle>
  <mat-datepicker #datepickerRef></mat-datepicker>
  <mat-error *ngIf="dateCtrl.errors?.required && deptCtrl.touched">Choose date</mat-error>
  </mat-form-field>

以及在我的app.component.ts中:

import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
import { AppDateAdapter, APP_DATE_FORMATS } from '../format-datepicker/format-datepicker.component';

@Component({
  selector: 'app-my selector',
  templateUrl: './my page.html',
  styleUrls: ['./my page.css'],
  providers: [
    {provide: DateAdapter, useClass: AppDateAdapter},
    {provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
  ]
})