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

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

问题描述

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

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接口作为模型而不是本机Date,除非您用作提供程序NgbDateNateiveAdapter或NgbDateNativeUTCAdapter

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}]

因此,您需要确定是否要使用元素{year:...,month:...,dat:...}或对象javascript的日期.

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

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

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天全站免登陆