v78
v78

Reputation: 2933

QDateTime: add current year automatically

I need to get a QDateTime object from the format "hh:mm:ss". where year, month and day should be taken from current date?

Would anyone suggest any cleaner solution other than prepending yyyy-mm-dd to the input string.

Upvotes: 0

Views: 2239

Answers (1)

Mike
Mike

Reputation: 8355

You can obtain the current date/time using QDateTime::currentDateTime(), then use setTime() to set the time you want:

QDateTime dateTime= QDateTime::currentDateTime();
dateTime.setTime(QTime::fromString("11:11:11", "hh:mm:ss"));

EDIT:

In order to get a QDateTime object when the format of the input string is "MM/dd hh:mm:ss", while setting the year as the current year, I would do something like this:

QDateTime dateTime= QDateTime::fromString("12/17 11:11:11", "MM/dd hh:mm:ss");
//get current date
QDate currentDate= QDate::currentDate();
//get read date
QDate readDate= dateTime.date();
//assign new date by taking year from currentDate, month and days from readDate
dateTime.setDate(QDate(currentDate.year(), readDate.month(), readDate.day()));

Please note that when a field is not present in the input format, QDateTime::fromString() uses some default values. In this case, the year is set to 1900 until it is assigned to the current year in the last line.

Upvotes: 5

Related Questions