如何将ngbDatepicker日期格式从JSON更改为YYYY / MM / DD

时间:2019-06-20 11:53:41

标签: javascript node.js angular

我正在使用ngbDatepicker,这给了我JSON日期格式,例如:

{ year: 2019, month: 6, day: 9 }

如何将其转换为YYYY / MM / DD? 我正在使用Angular 7。

我的代码如下:

<div class="input-group">
   <input class="form-control" placeholder="YYYY-MM-DD"
          (click)="d2.toggle()" (ngModelChange)="onDateSelection($event,'ToDate');"  name="d2" #c2="ngModel" [(ngModel)]="toDate" ngbDatepicker #d2="ngbDatepicker">
         <div class="input-group-append">
          <button class="btn btn-outline-secondar" 
             (click)="d2.toggle()" type="button">
           <i class="fa fa-calendar" aria-hidden="true"></i>
          </button>
         </div>
 </div>

3 个答案:

答案 0 :(得分:1)

有两个重要的类来管理ngbDate。一种用于格式化日期:DateParserFormater,另一种用于更改从ngb-datepicker获取/发送的值:DateAdapter。

因此,您可以创建customDateAdapter和customDateParserFormatter。但是,不用担心名称。只能有两个可注射类,例如

对于customDateAdapter

private bool _isEmailValid;

private bool BlockButton()
{
    return _isEmailValid && IsAppDeveloper == false && IsEndUser == false;
}

public string this[string columnName]
{
    get
    {
        string error = String.Empty;
        switch (columnName)
        {
            case "Email":
                string s = ValidateModelProperty(Email, columnName);
                _isEmailValid = string.IsNullOrEmpty(s);
                SignInCommand.RaiseCanExecuteChanged();
                return s;
        }

        return error;
    }
}

private string ValidateModelProperty(object value, string propertyName)
{
    ICollection<ValidationResult> validationResults = new List<ValidationResult>();
    ValidationContext validationContext = new ValidationContext(this, null, null) { MemberName = propertyName };
    if (!Validator.TryValidateProperty(value, validationContext, validationResults))
        foreach (ValidationResult validationResult in validationResults)
            return validationResult.ErrorMessage;
    return null;
}

是一个具有两个函数的可注入类,一个函数将NgbDate转换为字符串,另一个函数将字符串转换为NgbDate。记住,这会改变您的“模型”

对于CustomDateParserFormatter

@Injectable()
export class CustomDateAdapter {
  fromModel(value: string): NgbDateStruct
  {
     if (!value)
      return null
     let parts=value.split('/');
     return {year:+parts[0],month:+parts[1],day:+parts[2]}
  }

  toModel(date: NgbDateStruct): string // from internal model -> your mode
  {
    return date?date.year+"/"+('0'+date.month).slice(-2)
           +"/"+('0'+date.day).slice(-2):null
  }
}

再次具有两个可注入类,一个将NgbDate转换为字符串,另一个将字符串转换为NgbDate。请记住,这会更改日期的“格式”,如果需要,例如,可以使用dd / MM / yyyy-

然后只需将其添加为组件中的提供程序

@Injectable()
export class CustomDateParserFormatter {
  parse(value: string): NgbDateStruct
  {
    if (!value)
      return null
     let parts=value.split('/');
     return {year:+parts[0],month:+parts[1],day:+parts[2]} as NgbDateStruct

  }
  format(date: NgbDateStruct): string
  {
    return date?date.year+"/"+('0'+date.month).slice(-2)+"/"+('0'+date.day).slice(-2):null
  }
}

stackblitz中查看组件的定义,例如,可以选择

  providers: [{provide: NgbDateAdapter, useClass: CustomDateAdapter},
              {provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter}]

@Component({
  selector: 'ngbd-datepicker-adapter',
  templateUrl: './datepicker-adapter.html',
  providers: [{provide: NgbDateAdapter, useClass: NgbDateNativeAdapter}]
})

即使你可以写

@Component({
  selector: 'ngbd-datepicker-adapter',
  templateUrl: './datepicker-adapter.html',
  providers: [{provide: NgbDateAdapter, useClass: CustomDateAdapter},
          {provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter}]
})

要维护{year,month,day}之类的对象,但要更改“掩码”以及输入日期的方式

注意:您也可以将提供程序添加到模块中

答案 1 :(得分:0)

您需要的是

var date = object.year + '/' + object.month + '/'+ object.day

答案 2 :(得分:0)

如果使用日期字段,则需要在ts中绑定模型。在html中,像这样调用方法dateselect

 (dateSelect)="onDateSelect($event)"

完整代码:

 <input class="form-control"(dateSelect)="onDateSelect($event)"  id="TargetDate" placeholder="mm/dd/yyyy" name="targetDate" ngbDatepicker
          #date="ngbDatepicker"  />
          <div class="input-group-append">
            <button id="TargetDateButton" class="btn btn-outline-secondary" (click)="date.toggle()" type="button">
              <span class="oi oi-calendar"></span>
            </button>
          </div>

在类型脚本中,使用以下代码。这仅在使用Ngbdate选择器时适用。

 onDateSelect(event) {
  let year = event.year;
  let month = event.month <= 9 ? '0' + event.month : event.month;;
  let day = event.day <= 9 ? '0' + event.day : event.day;;
  let finalDate = year + "-" + month + "-" + day;
 }