7

I now, the question sounds rather silly, but I just can't get it to work. Worst example:

QString time_format = "yyyy-MM-dd  HH:mm:ss";
QDateTime a = QDateTime::currentDateTime();
QString as = a.toString(time_format);

qDebug() << as; // print "2014-07-16  17:47:04"

QDateTime b;
b.fromString(as,time_format);
assert(b.isValid()); // fails

I create a valid QDatetime, make a string out of it (that is correct) and try to turn it into a QDatetime again (using the same time_format-string). But suddenly, the string can't be parsed.

Any ideas?

FooTheBar
  • 818
  • 1
  • 9
  • 20

2 Answers2

9

fromString is a static function that returns the date; so you need to do:

QDateTime b = QDateTime::fromString(as,time_format);

in your code b never chaged from its default initialized state

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
2
QString as = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Rajkumar
  • 57
  • 2
  • In my case it didn't work with the ":" but when replaced with "-" it did. Whyever, just in case someone can't get it work as well. – Ben Dec 16 '22 at 11:48