I'm trying to write a calendar with timepicker, so that when you change the date, the time stays the same. Both fields (calendar and time) in html use the same variable (vm.inputDate
) and I don't want to change that.
Right now I have this function, that triggers on date change:
我正在尝试用timepicker写一个日历,这样当你改变日期时,时间保持不变。html中的两个字段(日历和时间)都使用相同的变量(vm.inputDate),我不想更改它。现在我有了这个函数,它在日期改变时触发:
vm.keepTimeUnchanged = function(changedDateTime, oldDateTime) {
var hours = oldDateTime.getHours();
var minutes = oldDateTime.getMinutes();
if (!moment(vm.inputDate).isSame((changedDateTime), 'day')) {
vm.inputDate = changedDateTime;
vm.inputDate.setHours(hours, minutes);
}
return vm.inputDate;
}
This works, but I would like to keep the time in exact same format, as in the original value, without getting separately seconds and milliseconds. Is there any way to do that? And is there any better way to perform the whole operation?
这是可行的,但我希望将时间保持在完全相同的格式中,就像在原始值中一样,不需要单独的秒和毫秒。有什么办法吗?有没有更好的方法来执行整个操作?
1 个解决方案
#1
2
It's either setting date in one moment or setting time in another, cannot be much better than that. Notice that when time is set, it may be desirable to set seconds and milliseconds as well.
它不是在某一时刻设定日期,就是在另一时刻设定时间,没有比这更好的了。请注意,在设置时间时,可能还需要设置秒和毫秒。
Moment API allows to do that in different flavours, like:
Moment API允许使用不同的口味,比如:
date1 = moment(date1.toArray().slice(0, 4).concat(
date2.toArray().slice(4)
);
Or:
或者:
let { years, months, date } = date1.toObject();
date1 = date2.clone().set({ years, months, date });
The same thing is less attractive in ES5, yet it's possible to make it look better with Lodash pick
:
同样的事情在ES5中不那么吸引人,但是用Lodash pick可以使它看起来更好:
date1 = date2.clone().set(_.pick(date1.toObject(), 'years', 'months', 'date'));
#1
2
It's either setting date in one moment or setting time in another, cannot be much better than that. Notice that when time is set, it may be desirable to set seconds and milliseconds as well.
它不是在某一时刻设定日期,就是在另一时刻设定时间,没有比这更好的了。请注意,在设置时间时,可能还需要设置秒和毫秒。
Moment API allows to do that in different flavours, like:
Moment API允许使用不同的口味,比如:
date1 = moment(date1.toArray().slice(0, 4).concat(
date2.toArray().slice(4)
);
Or:
或者:
let { years, months, date } = date1.toObject();
date1 = date2.clone().set({ years, months, date });
The same thing is less attractive in ES5, yet it's possible to make it look better with Lodash pick
:
同样的事情在ES5中不那么吸引人,但是用Lodash pick可以使它看起来更好:
date1 = date2.clone().set(_.pick(date1.toObject(), 'years', 'months', 'date'));