英文:
How to round off times (DayJs) by 1 minute, 5 minute, 15 minutes, 30 minutes, etc
问题
我在React Native中使用DayJs处理time。在选择两个不同的时间点来获取它们之间的差异时,代码似乎略微不一致。
大部分时间它都能正常工作,例如10:00和18:00 - 45分钟休息 = 7.25小时。但偶尔会出现7.233333...,因为选择的时间点是2023-07-04T08:00:58.183Z和2023-07-04T16:00:05.200Z,它们确实会转换成这个数值。
我是否可以在我的情况下将这些时间四舍五入到5分钟?
额外信息:
- 我正在使用
import DateTimePicker from '@react-native-community/datetimepicker';作为我的时间选择器。
英文:
I'm working with time in React Native using DayJs. When picking 2 different points in time to get the difference between the two, the code seems to be slightly inconsistent.
Most of the time it works well e.g. 10:00 and 18:00 - 45 min. break = 7.25 hours. But once in a while it gives 7.233333... because the points in time picked are 2023-07-04T08:00:58.183Z and 2023-07-04T16:00:05.200Z which indeed converts to that amount.
Is there a way for me to round off these times by (in my case) 5 minutes?
Extra info:
- I'm using
import DateTimePicker from '@react-native-community/datetimepicker';for mytimepicker
答案1
得分: 0
timeFormat="HH:mm:ss.SSS"
const roundToNearest5Minutes = (time) => {
const roundedMinute = Math.round(time.minute() / 5) * 5;
return time.startOf("minute").add(roundedMinute, "minute");
};
const calculateTimeDifference = (startTime, endTime) => {
if (startTime && endTime) {
const roundedStartTime = roundToNearest5Minutes(dayjs(startTime));
const roundedEndTime = roundToNearest5Minutes(dayjs(endTime));
const diffInSeconds = roundedEndTime.diff(
roundedStartTime,
"second",
true
);
const diffInHours = diffInSeconds / 3600;
setTimeDifference(diffInHours.toFixed(2));
}
};
英文:
timeFormat="HH:mm:ss.SSS"
const roundToNearest5Minutes = (time) => {
const roundedMinute = Math.round(time.minute() / 5) * 5;
return time.startOf("minute").add(roundedMinute, "minute");
};
const calculateTimeDifference = (startTime, endTime) => {
if (startTime && endTime) {
const roundedStartTime = roundToNearest5Minutes(dayjs(startTime));
const roundedEndTime = roundToNearest5Minutes(dayjs(endTime));
const diffInSeconds = roundedEndTime.diff(
roundedStartTime,
"second",
true
);
const diffInHours = diffInSeconds / 3600;
setTimeDifference(diffInHours.toFixed(2));
}
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论