1

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

Haris
  • 13,645
  • 12
  • 90
  • 121
  • 2
    The day names are localized according to the system's default locale settings, have you checked that? – Ediac Jun 19 '15 at 05:04
  • I didn't get you point? – Haris Jun 19 '15 at 05:15
  • 1
    Other than the locale settings 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 still wonder thoguh why the epoch is printed. Maybe that depends on the qt version you are using. – mfuchs Jun 19 '15 at 05:33
  • I am using QT 5.4.1 MSVC 2013 64 bit, Actually my input will be like that only, so are you saying this can create problem when I deploying my application from system to another, where system locale settings can be different. – Haris Jun 19 '15 at 05:42
  • @Haris exactly, see my answer for a way to make your code independent of the system's locale. – mfuchs Jun 19 '15 at 06:20
  • Thanks I will refer it. – Haris Jun 19 '15 at 06:22

1 Answers1

6

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.

mfuchs
  • 2,190
  • 12
  • 20