5

I have some code that reads a datetime from a sqlite database, the datetime is returned as a string. when I try to convert it to a date using QDateTime::FromString it returns an invalid date. Below is the time as returned from the database and conversion. Why is this failing to parse?

// -this is the value returned from the DB currentServerTime=2012-01-17 19:20:27.0

QString format("yyyy/MM/dd hh:mm:ss");
QString qCurrentServerTime(currentServerTime);
now = QDateTime::fromString(qCurrentServerTime, format);
Christian.K
  • 47,778
  • 10
  • 99
  • 143
user1127081
  • 161
  • 1
  • 3
  • 13

1 Answers1

10

No expert in QT, but if QDateTime::fromString() works as one would (reasonably) expect and according to this, you're not using the correct pattern.

You indicate the string read from the sqllite database is like "2012-01-17 19:20:27.0", then your format should be like yyyy-MM-dd HH:mm:ss.z.

In detail:

  • Your separator should by '-' not '/' (as you show in the example)
  • The time seems to be in 24 hours format (19 -> 7 p.m.) (so use HH instead of hh)
  • You have one digit for milliseconds, so add .z.
feedc0de
  • 3,646
  • 8
  • 30
  • 55
Christian.K
  • 47,778
  • 10
  • 99
  • 143
  • Sorry, I pasted the wrong time, I did modify the format to match what I posted and that works. moving back to my actual date/time I cannot get this to work. – user1127081 Jan 19 '12 at 15:31
  • @user1127081 So your actual string is formatted like you suggest with your format? Good. Then what doesn't work now? – Christian.K Jan 19 '12 at 15:35
  • Thanks, I posted the wrong datetime (the correct one 2012/01/17 12:00:00 AM) but you did lead me to my mistake(I also realize we have serveral d/t formats in our table). Below is the correct format. "MM/dd/yyyy hh:mm:ss AP" Thanks again – user1127081 Jan 19 '12 at 15:45
  • I found a much better way to manage the date conversion -Boost. PTime is much more forgiving in the event the format changes. boost::posix_time::ptime openTime(boost::posix_time::time_from_string("2012/01/17 12:00:00 AM"))); – user1127081 Feb 18 '12 at 03:51