QDateTime::fromString restituisce una data non valida, cosa mi sto perdendo?
Ho del codice che legge un datetime da un database sqlite, il datetime viene restituito come una stringa. quando provo a convertirlo in una data usando QDateTime::FromString restituisce una data non valida. Di seguito è riportato il tempo restituito dal database e dalla conversione.
Perché questo non riesce ad analizzare?
// -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);
Risposte:
Nessun esperto in QT, ma se QDateTime::fromString()
funziona come ci si aspetterebbe (ragionevolmente) e in base a ciò, non stai utilizzando lo schema corretto.
Indichi che la stringa letta dal database sqllite è come "2012-01-17 19:20:27.0", quindi il tuo formato dovrebbe essere come yyyy-MM-dd HH:mm:ss.z
.
In dettaglio:
- Il tuo separatore dovrebbe essere '-' non '/' (come mostri nell'esempio)
- L'ora sembra essere nel formato 24 ore (19 -> 19) (quindi usa
HH
invece dihh
) - Hai una cifra per millisecondi, quindi aggiungi
.z
.
Alcune risposte al codice
d the day as number without a leading zero (1 to 31) dd the day as number with a leading zero (01 to 31)
QLocale("en_US").toDate(QString(__DATE__).simplified(), "MMM d yyyy");