You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中使用owl-date-module向后端API发送epoch时间

1. change事件无法触发的解决方法

owl-date-time是自定义组件,选择日期后不会触发原生input的change事件,你需要把绑定的(change)换成组件自带的(dateTimeChange)事件即可触发回调。

2. Payload带null列表的问题

你现在把起止时间拆成了两个独立输入框,分别绑定了rangeFrom和rangeTo模式,每个输入框绑定的ngModel拿到的应该是单个Date对象,不是range模式下的[开始时间, 结束时间]数组。你原来的代码里还在遍历数组,就会出现多余的空值结构,提交的时候自然会带null。提交的时候不要直接传组件返回的Date对象,用转换好的epoch数值就可以解决。

3. 时间转epoch格式

选中的Date对象直接调用getTime()就能拿到13位毫秒级的epoch时间戳,如果后端要求秒级的话,除以1000取整就行:Math.floor(selectedDate.getTime() / 1000)。


修改后HTML代码

<div class="form-group row">
  <label class="col-md-3 col-form-label text-right">
    开始时间
    <span class="colorRed">*</span>
  </label>
  <div class="col-lg-5 col-sm-11">
    <input type="text" id="start_time" style="height: 36px;"
     class="form-control" [selectMode]="'rangeFrom'" name="start_time"
     placeholder="请选择开始时间" [(ngModel)]="startTime"
     [owlDateTimeTrigger]="dt1" [owlDateTime]="dt1"
     (dateTimeChange)="getTime($event, 'from')" [max]="maxFrom"
     autocomplete="off" required>
    <owl-date-time #dt1></owl-date-time>
  </div>
</div>
<div class="form-group row">
  <label class="col-md-3 col-form-label text-right">
   结束时间
   <span class="colorRed">*</span>
  </label>
  <div class="col-lg-5 col-sm-11">
   <input type="text" id="stop_time" style="height: 36px;"
    class="form-control" [selectMode]="'rangeTo'" name="stop_time"
    placeholder="请选择结束时间" [(ngModel)]="stopTime"
    [owlDateTimeTrigger]="dt2" [owlDateTime]="dt2"
    (dateTimeChange)="getTime($event, 'to')" [min]="minTo"
    autocomplete="off" required>
   <owl-date-time #dt2></owl-date-time>
  </div>
</div>

修改后TS代码

// 新增两个变量存储转换后的epoch时间,提交接口时直接传这两个值即可
startTimeEpoch: number;
endTimeEpoch: number;

getTime(selectedDate: Date, type: 'from' | 'to') {
  console.log("Hello Chuckles");
  // 转换为epoch时间,如需秒级则改为 Math.floor(selectedDate.getTime() / 1000)
  const epoch = selectedDate.getTime();
  if (type === 'from') {
    this.startTimeEpoch = epoch;
    // 限制结束时间的可选最小值为选中的开始时间
    this.minTo = new Date(epoch);
  } else {
    this.endTimeEpoch = epoch;
    // 限制开始时间的可选最大值为选中的结束时间
    this.maxFrom = new Date(epoch);
  }
}

相关截图

日期选择器效果:
DatePicker

原异常Payload示例:
Payload

内容的提问来源于stack exchange,提问作者Anuj Kalra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:48:00