【问题标题】:Round a Date() to the nearest 5 minutes in javascript在 javascript 中将 Date() 舍入到最接近的 5 分钟
【发布时间】:2023-03-16 07:44:01
【问题描述】:

使用Date() 实例,我如何将时间四舍五入到最接近的五分钟?

例如:如果是下午 4:47。它会将时间设置为下午 4 点 45 分

【问题讨论】:

标签: javascript


【解决方案1】:

如果你已经有一个Date 对象,那就很简单了:

var coeff = 1000 * 60 * 5;
var date = new Date();  //or use any other date
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff)

【讨论】:

  • @Jick 如果某个答案对您有用,那么您应该单击绿色对勾将其标记为已接受的答案。这样一来,您和回答者的声誉都会得到一点提升,而且您的内心也会有一种很好的模糊感
  • 如果你想一直四舍五入。只需使用Math.ceil 而不是Math.round。例如,这样一来,您总是可以四舍五入 10 分钟。
  • 你甚至不需要使用getTime,因为它会隐式使用valueOf,例如new Date(Math.round(date / coeff) * coeff)
  • TypeScript 抱怨左手算术,因此添加 getTime() 实际上修复了该错误。并不是说我提倡在普通应用程序中使用 TS,而是我正在构建一个金融应用程序,所以我要格外小心。
【解决方案2】:

使用 ES6 和部分函数,​​它可以很优雅。选择是否需要舍入到最接近或始终向下/向上:

const roundTo = roundTo => x => Math.round(x / roundTo) * roundTo;    
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;

const roundTo5Minutes = roundTo(1000 * 60 * 5);
const roundDownTo5Minutes = roundDownTo(1000 * 60 * 5);
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);

const now = new Date();
const msRound = roundTo5Minutes(now)
const msDown = roundDownTo5Minutes(now)
const msUp = roundUpTo5Minutes(now)

console.log(now);
console.log(new Date(msRound));
console.log(new Date(msDown));
console.log(new Date(msUp));

【讨论】:

  • 很好的答案!我想四舍五入到最近的 15 分钟,这样就完成了
【解决方案3】:

四舍五入到最近的 x 分钟

这是一种将日期对象四舍五入到最接近的 x 分钟的方法,或者如果您不给它任何日期,它会将当前时间四舍五入。

let getRoundedDate = (minutes, d=new Date()) => {

  let ms = 1000 * 60 * minutes; // convert minutes to ms
  let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);

  return roundedDate
}


// USAGE //

// Round existing date to 5 minutes
getRoundedDate(5, new Date()); // 2018-01-26T00:45:00.000Z

// Get current time rounded to 30 minutes
getRoundedDate(30); // 2018-01-26T00:30:00.000Z

【讨论】:

  • 注意:这适用于 UTC 时间。截断到最近的五分钟并不重要,但如果截断到本地时间的小时则不起作用,因为某些时区不是完整的小时。
【解决方案4】:

Date-fns 现在有一个函数可以对日期进行四舍五入。见https://date-fns.org/v2.21.3/docs/roundToNearestMinutes

const roundToNearestMinutes = require('date-fns/roundToNearestMinutes')
console.log(roundToNearestMinutes(new Date(), {nearestTo: 5}));
// e.g. 2021-05-19T22:45:00.000Z

【讨论】:

    【解决方案5】:

    可能效率较低,但这里有另一种选择:

    debug('Current timestamp:', timestamp);
    
    timestamp.setMilliseconds(0);
    timestamp.setSeconds(0);
    timestamp.setMinutes(Math.round(timestamp.getMinutes() / 5) * 5);
    
    debug('Rounded timestamp:', timestamp);
    
    Current timestamp: 2019-10-22T09:47:17.989Z
    Rounded timestamp: 2019-10-22T09:45:00.000Z
    

    【讨论】:

      【解决方案6】:

      使用此方法获取下一个使用纯JS的5分钟循环

      function calculateNextCycle(interval) {
          const timeStampCurrentOrOldDate = Date.now();
          const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
          const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
          const mod = Math.ceil(timeDiff / interval);
          return new Date(timeStampStartOfDay + (mod * interval));
      }
      
      console.log(calculateNextCycle(5 * 60 * 1000)); // pass in milliseconds

      【讨论】:

        【解决方案7】:

        我知道回答有点晚了,但也许它可以帮助某人。如果您按以下方式记录

        new Date().getMinutes()
        

        您可以在最后 5 分钟内完成

        new Date().getMinutes() - (new Date().getMinutes()%5)
        

        【讨论】:

          【解决方案8】:

          最近发现了一种将日期四舍五入到时间范围的非常有效的方法

          简而言之:

          // minutes
          var tf = 15; // 5,10,13,15, 60, - what ever you want
          var dt = DateTime.UtcNow;
          var minues = dt.TimeOfDay.TotalMinutes; // use TotalMinutes, TotalSecibds, TotalMillisecons  and etc
          var roundedMinutes = (minues - (minues%tf));
          var roundedDate = dt.Date.AddMinutes(a);
          

          我在 LINQPad 中的一些测试

          // minutes
          var tf = 15; // 5,10,13,15, 60, - what ever you want
          var dt = DateTime.UtcNow;
          var minues = dt.TimeOfDay.TotalMinutes;
          dt.Dump();
          minues.Dump();
          (ms%tf).Dump();
          var a = (minues - (minues%tf));
          a.Dump();
          dt.Date.AddMinutes(a).Dump();
          

          输出:

          13.07.2018 7:43:58 - current date
          463,981443103333 - total mins
          13,9814431033333 - rest
          450 - rounded minutes value
          13.07.2018 7:30:00 - rounded date
          

          【讨论】:

          • 这在我看来像 C#,问题是关于 JavaScript。
          【解决方案9】:

          有一个NPM package @qc/date-round 可以使用。假设您有一个要舍入的 Date 实例

          import { round } from '@qc/date-round'
          
          const dateIn = ...; // The date to be rounded
          const interval = 5 * 60 * 1000; // 5 minutes
          const dateOut = round(dateIn, interval)
          

          那么你可以使用date-fns来格式化日期

          import format from 'date-fns/format';
          
          console.log(format(dateOut, 'HH:mm')) // 24-hr
          console.log(format(dateOut, 'hh:mm a')) // 12-hr
          

          【讨论】:

            【解决方案10】:

            一行解决方案(向上或向下舍入):

            const fixedTime = (isRoundUp ? Math.ceil : Math.floor)(time / 60_000 / minutesRange)) * 60_000 * minutesRange;
            
            // minutesRange: number -> 1, 5, 15, 30, etc // minutes
            // isRoundUp: boolean
            // time: number // millis
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-01-29
              • 2011-01-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多