我正在尝试用 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 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 日:
- 4 月的日期设置为 31,但该日期不存在,因此滚动到 5 月 1 日
- 月份设置为三月
- 年份设置为任意
所以你最终得到的日期是 3 月 1 日。一次性设置值可以解决这个问题:
- (2020-04-01).setFullYear(2020, 2, 31) -> 2020-03-31
设置年份时,还可以设置月份和日期,设置月份时,可以设置月份和日期。同样对于时间,设置小时可以设置小时、分钟、秒和毫秒。设置分钟可以设置分、秒、毫秒等
关于javascript - 修改日期时出现问题(修改错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60939898/