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

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

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

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));
    }
};

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:

确定