QDateTime Conversion

佐手、 提交于 2019-12-11 19:27:53

问题


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:


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.



来源:https://stackoverflow.com/questions/30930085/qdatetime-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!