Search code examples
javascriptmomentjsphp-carbon

round carbon date to closest previous 6 hour mark


i have an application that executes a cron job every 6 hours:

00:00, 06:00, 12:00, 18:00

How do i round the current time to the lowest matching hour of the above?

So if its 13:05 now, it should return 12:00

edit: i meant in javascript, not in php. updated my question


Solution

  • You can use this function and it is without moment.js

    function getRoundedTime(){
      var d = new Date();
      var now = d.getHours();
      if(now > 6){
        var roundedTime = now - (now % 6);
        var stringTime = roundedTime.toString().concat(":00");
        return stringTime;
      }
      if(now < 6){
        return "00:00";
      }
      if(now % 6 === 0) {
        return "0" + now.toString().concat(":00");
      }
    }
    
    getRoundedTime();
    

    Or if you want moment.js then import moment and inside function declare now like this var now = moment().hour();