navzy
navzy

Reputation: 11

How to round up the time to next hour in QT?

This is the code:

startDate->setDateTime( QDateTime::currentDateTime() );
finishDate->setDateTime( QDateTime::currentDateTime() );
finishDate->setDateTime(startDate->dateTime().addSecs( 3600 ));

For example the time now is 13:34

I need the start time to be rounded up to 14:00 Also the finish time to rounded up to 15:00

Anyone have any ideas on how to do this? Can please provide an example also? thanks :D

Upvotes: 1

Views: 1079

Answers (1)

Googie
Googie

Reputation: 6017

Assuming you will always operate on recent dates (never older than 1970) you can use so called unixtime and simple math, like this:

uint unixtime  = QDateTime::currentDateTime().toTime_t(); // current unix time
uint roundHour = unixtime + (3600 - unixtime % 3600); // round it up to an hour
QDateTime start;
QDateTime hourLater;
start.setTime_t(roundHour); // set start datetime to rounded time
hourLater.setTime_t(roundHour + 3600); // set finish time to one hour later
startDate->setDateTime(start);
finishDate->setDateTime(hourLater);

Upvotes: 5

Related Questions