QDateTime::fromString not accepting my QString?

QDateTime::fromString not accepting my QString?

本文关键字:QString my not fromString QDateTime accepting      更新时间:2023-10-16

我有一个。txt文件,里面填充了如下所示的行:

  • 2011-03-03 03.33.13.222 4 2000信息商业…等鼓励性
  • 2011-03-03 03.33.13.333 4 2000信息商业…等鼓励性
  • 2011-03-03 03.33.13.444 4 2000信息业务…等鼓励性

在我的代码中的某个点,我做了一些计算和搜索,在那里我只从每行的开头提取日期。现在,当我正确地定位在文件的开头时,我只提取日期和时间(以毫秒计)"ex: 2011-03-03 03.33.13.444"并转换为QDateTime对象。

假设我的文件指针正确地定位在某一行的开头,使用readLine读取我的日期时间文本行并转换为QDateTime对象

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

绝对正确。

但是,这里有一个问题:

当我这样做的时候:

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 ????

但是如果我这样做了:

dt = QDateTime::fromString("2011-03-03 03.33.13.444","yyyy-MM-dd HH.mm.ss.zzz");那么一切都好了。

我的QString可能有什么问题?我需要追加到strMyDateTime一个""还是我需要一些其他转换??

您的字符串有额外的字符,最可能是开始的空格。你的格式字符串是23个字符,你使用left(24),所以必须有一个额外的字符。你在Stephen Chu的回答的评论中说,将24改为23会丢失最后一个毫秒字符,所以额外的字符必须在开头。

"2011-03-03 03.33.13.444"实际上是23个字符长,而不是24个字符。您提取的字符串可能在末尾有一个额外的字符?