QDateTime Conversion

3.9k views Asked by At

I need to convert the String variable to QDateTime format

my code looks

QString date ="Thu Jun 18 2015";
QDateTime tmp = QDateTime::fromString(date,"ddd MMM dd yyyy HH:mm:ss");

But the result is Thu Jan 1 00:00:00 1970.

Later I have to convert this date in to foramt yyyy-MM-dd HH:mm:ss, so as a first step I have convert the string in to QDateTime then I have to convert to the final format, is there anything mistake with the above code?

Any help will be appreciated.

Thanks Haris

1

There are 1 answers

0
mfuchs On BEST ANSWER

Your date string does not include a time, while you mentioned that you want one, this will fail at least in Qt 5.4 . I don't know though why you get the epoche outputed, maybe that is dependant on your Qt version.

Your date format is also locale dependent. See for example the doucmentation for "ddd" in QDateTime::fromString:

the abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName().

Which unfortunately is not that clear, while it is more clear for QDateTime::toString:

the abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses the system locale to localize the name, i.e. QLocale::system().

For example, in my locale (German, Austria) "ddd" for Thursday results in "Do." which is different from "Thu" and makes it impossible to parse English abbrevations with that locale.

To ensure you are using the correct locale when reading or writing locale dependent output use QLocale. In your case that would be QLocale::toDateTime:

QLocale locale(QLocale::English, QLocale::UnitedStates);
QDateTime dt = locale.toDateTime("Jun 18 2015", "MMM dd yyyy");

Then if you also want locale dependent output use QLocale::toString.