Home > database >  How to convert ISO string format date time to next hour
How to convert ISO string format date time to next hour

Time:12-20

I am using the following function to convert my date in RFC3339. I want it to convert in upper limit.

Can anyone assist me, how do I convert it to upper limit?

 const date = new Date();
    // RFC 3339 format
    const targetTime = date.toISOString();
Current output is 

2022-12-20T05:26:12.968Z

Expected output should be

2022-12-20T06:00:00Z

CodePudding user response:

See this answer, very similar but you can replace Math.round with Math.ceil to round up like you want:

const roundDateToNextHour = (date: Date) => {
    date.setHours(date.getHours()   Math.ceil(date.getMinutes() / 60));
    date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
    return date;
}

CodePudding user response:

If the intention is to the next full UTC hour, test if UTC minutes, seconds or milliseconds are greater than zero. If any of them are, increment the hour and zero the other values, e.g.:

// If the provided date is not exactly on the UTC hour, 
// return a date that is the next full UTC hour after
// the provided date.
function toFullUTCHour(date) {
  let d = new Date( date);
  d.setUTCHours(d.getUTCHours()   (d.getUTCMinutes() || d.getUTCSeconds() || d.getUTCMilliseconds? 1 : 0), 0,0,0);
  return d;
}

let d = new Date()
console.log(d.toISOString()   '\n'  
  toFullUTCHour(d).toISOString());

  • Related