我有一个Material Datepicker,我想从中获取没有时间戳的日期。由于我的时区是GMT + 2,因此API总是收到类似于03.04.2018 22:00:00 UTC的内容,但我想将日期保存在本地。
我的日期拣货员:“2018年4月11日星期三00:00:00 GMT + 0200(中欧夏令时间)”
<div class="input-group">
<input matInput [matDatepicker]="start" readonly="readonly" class="form-control" formControlName="start" name="start" >
<div class="date__picker__button">
<mat-datepicker-toggle matSuffix [for]="start"></mat-datepicker-toggle>
<mat-datepicker #start [disabled]="!formulationForm.enabled"></mat-datepicker>
</div>
</div>
可以在调用API之前格式化datepicker值,但我希望有更好的解决方案。
答案 0 :(得分:0)
是的,我知道有两种方法可行。
// date.helpers.ts
import { formatDate } from '@angular/common';
import { Injectable } from '@angular/core';
import { NativeDateAdapter } from '@angular/material/core';
export const PICK_FORMATS = {
parse: { dateInput: { month: 'short', year: 'numeric', day: 'numeric' } },
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' }
}
};
@Injectable({
providedIn: 'root'
})
export class PickDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
return formatDate(date, 'dd/MM/yyyy', this.locale);;
} else {
return date.toDateString();
}
}
}
// add this to your.module.ts
providers: [
NomineeService,
{ provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { appearance: 'legacy' } },
{ provide: DateAdapter, useClass: PickDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: PICK_FORMATS },
]
// shared.service.ts
formatDate(date): string {
const _date = new Date(date);
const day = _date.getDate();
const month = _date.getMonth() + 1;
const year = _date.getFullYear();
return `${year}-${month}-${day}`;
}
formatTime(date: Date): string {
const _date = new Date(date);
const hours = _date.getHours()
const minutes = _date.getMinutes();
const seconds = _date.getSeconds();
return `${hours}:${minutes}:${seconds}`;
}
toDateTimestamp(date: Date): string {
const dateStamp = this.formatDate(date);
const timeStamp = this.formatTime(date);
return `${dateStamp} ${timeStamp}`
}
calculateDays(fromDate, toDate): number {
const FromDate = new Date(fromDate);
const ToDate = new Date(toDate);
const difference = ToDate.getTime() - FromDate.getTime();
const days = Math.round((difference / (1000 * 60 * 60 * 24)));
return days;
}
答案 1 :(得分:0)
您可以使用 moment
的 node.js 库:
npm i moment --save
之后你可以这样做;
let formatted_date = moment(var_to_format).format("YYYY-MM-DD");