Frage

I have a .txt file which is filled with lines like this below:

  • 2011-03-03 03.33.13.222 4 2000 Information BUSINESS ...etc blabla
  • 2011-03-03 03.33.13.333 4 2000 Information BUSINESS ...etc blabla
  • 2011-03-03 03.33.13.444 4 2000 Information BUSINESS ...etc blabla

In some point in my code i do some calculating and seeking, where i extract only the dates from the beginning of each line. Now, when i'm positioned correct at the beginning of a file, i extract only the date and time (with the miliseconds) "ex: 2011-03-03 03.33.13.444" and convert to a QDateTime object.

Assuming that my file pointer is positioned correct at the beginning of a certain line, with readLine i read my datetime text line and convert to QDateTime object

QDateTime dt;
char lineBuff[1024];
qint64 lineLength;
lineLength=file.readLine(lineBuff, 24); 
dt = QDateTime::fromString(QString(lineBuff),"yyyy-MM-dd HH.mm.ss.zzz");

This is apsolutely correct.

But, here is the problem:

When i do the same like this:

QDateTime dt;
QByteArray baLine;
char lineBuff[1024];
file.seek(nGotoPos); //QFile, nGotoPos = a position in my file
QString strPrev(baLine); // convert bytearry to qstring -> so i can use mid()

// calculate where the last two newline characters are in that string
int nEndLine = strPrev.lastIndexOf("\n");
int nStartLine = strPrev.lastIndexOf("\n", -2);

QString strMyWholeLineOfTextAtSomePoint = strPrev.mid(nStartLine,nEndLine);
QString strMyDateTime = strMyWholeLineOfTextAtSomePoint.left(24); 

// strMyDateTime in debug mode shows me that it is filled with my string 
// "ex: 2011-03-03 03.33.13.444" 

// THE PROBLEM
// But when i try to covert that string to my QDateTime object it is empty
dt = QDateTime::fromString(strMyDateTime ,"yyyy-MM-dd HH.mm.ss.zzz");

dt.isValid() //false
dt.toString () // "" -> empty ????

BUT IF I DO:

dt = QDateTime::fromString("2011-03-03 03.33.13.444","yyyy-MM-dd HH.mm.ss.zzz"); Then everything is alright.

What could posibly be the problem with my QString? Do i need to append to strMyDateTime a "\0" or do i need some other conversions??

War es hilfreich?

Lösung

Your string has extra characters, most likely a space in the beginning. Your format string is 23 characters and you are using left(24), so there must be one extra character. You said in the comment to Stephen Chu's answer that changing 24 to 23 dropped the last millisecond character, so the extra character must be in the beginning.

Andere Tipps

"2011-03-03 03.33.13.444" is actually 23 characters long, not 24. Your extracted string probably has a extra character at the end?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top