【问题标题】:Problem while modifying a date (modification is wrong)修改日期时出现问题(修改错误)
【发布时间】:2020-03-30 21:34:29
【问题描述】:

我正在尝试在 Angular 中制作日历。为此,我实现了一个拖放功能,以便能够将一个约会从一天移动到另一个约会。

但是我有一些奇怪的事情,当我尝试移动约会时它似乎有效,但是当我尝试将它从 4 月 1 日移动到 3 月 31 日时,日期被修改为 3 月 1 日。

当我放弃约会时,我会用我的约会数据和新的一天发出更改:

drop(evt) {
    let schedule: Schedule;
    schedule = evt.data.schedule;

    // Emit change
    this.scheduleChange.emit({schedule, day: this.day});
  }

然后我编辑我的约会:

  scheduleChanged(evt) {
    const schedule = this.createScheduleFromObject(evt.schedule);
    const day = evt.day;

    console.log(day);

    if (this.isSameDate(schedule.start, schedule.end)) {
      schedule.start.setDate(day.getDate());
      schedule.start.setMonth(day.getMonth())
      schedule.start.setFullYear(day.getFullYear());

      schedule.end.setDate(day.getDate());
      schedule.end.setMonth(day.getMonth());
      schedule.end.setFullYear(day.getFullYear());
      console.log(schedule);
    }
  }

我认为问题在于我将对象转换为 Schedule 类时:

 createScheduleFromObject(obj: any) {
    const schedule: Schedule = Object.assign(new Schedule(null, '', '', '', new Date(), new Date()), obj);
    console.log(obj.start);
    schedule.start = new Date(obj.start);
    schedule.end = new Date(obj.end);
    console.log(schedule.start);

    return schedule;
  }

这个函数返回好的日期这里是控制台日志的输出:

2020-04-01T21:31:49.640Z
Wed Apr 01 2020 23:31:49 GMT+0200

但是当我在 scheduleChanged 函数中修改它时,即使那天是 3 月 31 日,就像我在控制台日志中看到的那样:

Tue Mar 31 2020 00:00:00 GMT+0200

我的日程安排的开始日期设置为:

Sun Mar 01 2020 23:33:19 GMT+0100

为什么?

【问题讨论】:

    标签: javascript angular typescript date


    【解决方案1】:

    我怀疑这是 Javascript setMonth shows improper date 的副本。在您的情况下,可能发生的情况是将 4 月的日期移至 3 月 31 日,您将 4 月的日期设置为不存在的日期,因此它会滚动到下个月。

    在一次设置一个日期的值时,您可能会遇到开始日期的日期在设置的月份中不存在的问题。因此,当将日期的值设置为新值时,请一次性完成所有操作,而不是:

      schedule.start.setDate(day.getDate());
      schedule.start.setMonth(day.getMonth())
      schedule.start.setFullYear(day.getFullYear());
    

    做:

      schedule.start.setFullYear(day.getFullYear(), day.getMonth(), day.getDate());
    

    因此,在您的情况下,将日期从 4 月 1 日移至 3 月 31 日:

    1. 4 月日期设置为 31 日,该日期不存在,因此滚动到 5 月 1 日
    2. 月份设置为三月
    3. 年份设置为任意值

    所以你最终得到了一个 3 月 1 日的日期。一次性设置值可以解决这个问题:

    1. (2020-04-01).setFullYear(2020, 2, 31) -> 2020-03-31

    设置年份的时候可以设置月份和日期,设置月份的时候可以设置月份和日期。同样对于时间,设置小时可以设置小时、分钟、秒和毫秒。设置分钟可以设置分、秒、毫秒等。

    【讨论】:

    • 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多