NgbDatePicker 没有使用 NgbDateParserFormatter 正确格式化日期 [英] NgbDatePicker doesn't format Date correctly using NgbDateParserFormatter

查看:25
本文介绍了NgbDatePicker 没有使用 NgbDateParserFormatter 正确格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,这个微不足道的任务有一些问题,但似乎这是使用此 ParserFormater 在输入字段中格式化日期的推荐方法.当用户从日历中选择日期时,日期以dd-MM-yyyy"格式正确显示在输入字段框中(如我所愿),但是当我将详细信息保存到数据库中时,日期被返回以某种奇怪的格式返回,它甚至不正确.我得到这样的信息:'1907-02-09T00:00:00'......如果有人能指出我正确的方向,这里是下面的前端代码:

//html<div class="form-group"><label for="motDate">MOT 日期</label><input type="text" class="form-control" placeholder="dd-mm-yyyy"ngbDatepicker #d="ngbDatepicker" (focus)="d.open()" (dateSelect)="onMOTDateSelected($event)" #motDate><input type="hidden" [(ngModel)]="model.motDate" name="motDate"/>

//打字稿导出类 AppComponent {模型:车辆 = <车辆>{};@ViewChild('motDate') motDatePicker;ngOnInit() {this.motDatePicker.nativeElement.value = this.model.motDate;}onMOTDateSelected(e) {console.log("MOT 日期选择");this.model.motDate = new Date(e.day, e.month, e.year);}}@Injectable()导出类 NgbDateCustomParserFormatter 扩展 NgbDateParserFormatter {解析(值:字符串):NgbDateStruct {如果(值){const dateParts = value.trim().split("/");if (dateParts.length === 1 && isNumber(dateParts[0])) {返回 { 日:toInteger(dateParts[0]),月:空,年:空};} else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {返回 {日:toInteger(dateParts[0]),月份:toInteger(dateParts[1]),年份:空};} else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {返回 {日:toInteger(dateParts[0]),月份:toInteger(dateParts[1]),年份:toInteger(dateParts[2])};}}返回空;}格式(日期:NgbDateStruct):字符串{归期 ?`${isNumber(date.day) ?padNumber(date.day) : `""}/${isNumber(date.month) ?padNumber(date.month) : ""}/${date.year}` : "";`}}导出函数 toInteger(value: any): number {返回 parseInt(`${value}`, 10);}导出函数 isNumber(value: any): value is number {返回 !isNaN(toInteger(value));}导出函数 padNumber(value: number) {如果(isNumber(值)){返回`0${value}`.slice(-2);} 别的 {返回 "";}}//车辆模型导出接口 Vehicle {motDate:日期;}

解决方案

Zokes, NgbDate NgbDateStruct 接口作为模型而不是本机 Date 除非您用作提供者 NgbDateNateiveAdapter 或 NgbDateNativeUTCAdapter

providers: [{provide: NgbDateAdapter, useClass: NgbDateNativeAdapter}]

因此,您需要决定是否要使用元素 {year:...,month:...,dat:...} 或对象 Date of javascript.

您通常使用字符串或使用对象日期(或日期时间)将数据存储在 dbs 中,并且您以相同的方式接收.所以我喜欢在自己的服务中转换日期.想象一下,您收到的服务数据带有属性日期"

getData(key:any){this.get(...).pipe(map((响应)=>{让parts=response.date.split('T')[0].split('-')response.date={year:+parts[0],month:+parts[1],day:+parts[2]}返回响应;}))}获取列表(键:任意){this.get(...).pipe(map((response:any[])=>{response.forEach(x=>{let parts=x.date.split('T')[0].split('-')x.date={year:+parts[0],month:+parts[1],day:+parts[2]}})返回响应;}))}更新数据(数据){data.date=data.year+"-"+data.month+"-"+data.daythis.http.post(....,data)}

Unfortunately having some issues with this trivial task, but it seems this is a recommended way of formating the date in a input field, using this ParserFormater. When a user chooses the date from the calendar, the date is shown correctly in the input field box, in 'dd-MM-yyyy' format (as I want), but when I save the details into a database the date is being returned back in some weird format and it's not even correct. I get something like this: '1907-02-09T00:00:00'......here is the front end code below if someone can point me in the right direction:

//html
      <div class="form-group">
        <label for="motDate">MOT Date</label>
        <input type="text" class="form-control" placeholder="dd-mm-yyyy"
               ngbDatepicker #d="ngbDatepicker" (focus)="d.open()" (dateSelect)="onMOTDateSelected($event)" #motDate>
        <input type="hidden" [(ngModel)]="model.motDate" name="motDate"/>
      </div>

//typescript
export class AppComponent {
  model: Vehicle = <Vehicle>{};

  @ViewChild('motDate') motDatePicker;

  ngOnInit() {
    this.motDatePicker.nativeElement.value = this.model.motDate;
  }

  onMOTDateSelected(e) {
    console.log("MOT Date Selected");
    this.model.motDate = new Date(e.day, e.month, e.year);
  }
}

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct {
    if (value) {
      const dateParts = value.trim().split("/");
      if (dateParts.length === 1 && isNumber(dateParts[0])) {
        return { day: toInteger(dateParts[0]), month: null, year: null };
      } else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
        return {
          day: toInteger(dateParts[0]),
          month: toInteger(dateParts[1]),
          year: null
        };
      } else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
        return {
          day: toInteger(dateParts[0]),
          month: toInteger(dateParts[1]),
          year: toInteger(dateParts[2])
        };
      }
    }
    return null;
  }

  format(date: NgbDateStruct): string {
    return date ? `${isNumber(date.day) ? padNumber(date.day) : `""}/${isNumber(date.month) ? padNumber(date.month) : ""}/${date.year}` : "";`
  }
}

export function toInteger(value: any): number {
  return parseInt(`${value}`, 10);
}

export function isNumber(value: any): value is number {
  return !isNaN(toInteger(value));
}

export function padNumber(value: number) {
  if (isNumber(value)) {
    return `0${value}`.slice(-2);
  } else {
    return "";
  }
}

// vehicle model
export interface Vehicle {
  motDate: Date;
}

解决方案

Zokes, NgbDate NgbDateStruct interface as a model and not the native Date unless you use as provider NgbDateNateiveAdapter or NgbDateNativeUTCAdapter

providers: [{provide: NgbDateAdapter, useClass: NgbDateNativeAdapter}]

So you need decided if you want work with elements {year:...,month:...,dat:...} or with objects Date of javascript.

You normally store the data in a dbs using a string or using an Object Date (or DateTime), and you received in the same way. So I like transform the dates in the own service. Imagine that you received in your service data with a propertie "date"

getData(key:any)
{
     this.get(...).pipe(map((response)=>{
        let parts=response.date.split('T')[0].split('-')
        response.date={year:+parts[0],month:+parts[1],day:+parts[2]}
        return response;
     }
     ))
}
getList(key:any)
{
     this.get(...).pipe(map((response:any[])=>{
        response.forEach(x=>{
         let parts=x.date.split('T')[0].split('-')
         x.date={year:+parts[0],month:+parts[1],day:+parts[2]}
        })
        return response;
     }
     ))
}
updateData(data)
{
    data.date=data.year+"-"+data.month+"-"+data.day
    this.http.post(....,data)
}

这篇关于NgbDatePicker 没有使用 NgbDateParserFormatter 正确格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆