如何通过 DayJs 将时间舍入到1分钟、5分钟、15分钟、30分钟等。

huangapple go评论117阅读模式
英文:

How to round off times (DayJs) by 1 minute, 5 minute, 15 minutes, 30 minutes, etc

问题

我在React Native中使用DayJs处理time。在选择两个不同的时间点来获取它们之间的差异时,代码似乎略微不一致。

大部分时间它都能正常工作,例如10:0018:00 - 45分钟休息 = 7.25小时。但偶尔会出现7.233333...,因为选择的时间点是2023-07-04T08:00:58.183Z2023-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 my timepicker

答案1

得分: 0

  1. timeFormat="HH:mm:ss.SSS"
  2. const roundToNearest5Minutes = (time) => {
  3. const roundedMinute = Math.round(time.minute() / 5) * 5;
  4. return time.startOf("minute").add(roundedMinute, "minute");
  5. };
  6. const calculateTimeDifference = (startTime, endTime) => {
  7. if (startTime && endTime) {
  8. const roundedStartTime = roundToNearest5Minutes(dayjs(startTime));
  9. const roundedEndTime = roundToNearest5Minutes(dayjs(endTime));
  10. const diffInSeconds = roundedEndTime.diff(
  11. roundedStartTime,
  12. "second",
  13. true
  14. );
  15. const diffInHours = diffInSeconds / 3600;
  16. setTimeDifference(diffInHours.toFixed(2));
  17. }
  18. };
英文:

timeFormat="HH:mm:ss.SSS"

  1. const roundToNearest5Minutes = (time) => {
  2. const roundedMinute = Math.round(time.minute() / 5) * 5;
  3. return time.startOf("minute").add(roundedMinute, "minute");
  4. };
  5. const calculateTimeDifference = (startTime, endTime) => {
  6. if (startTime && endTime) {
  7. const roundedStartTime = roundToNearest5Minutes(dayjs(startTime));
  8. const roundedEndTime = roundToNearest5Minutes(dayjs(endTime));
  9. const diffInSeconds = roundedEndTime.diff(
  10. roundedStartTime,
  11. "second",
  12. true
  13. );
  14. const diffInHours = diffInSeconds / 3600;
  15. setTimeDifference(diffInHours.toFixed(2));
  16. }
  17. };

huangapple
  • 本文由 发表于 2023年7月5日 01:33:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76614811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定