我有一个.txt文件,其中填充了如下所示的行:
2000年信息业务blabla
在我的代码中的某个点,我做一些计算和寻找,其中我只提取日期从每一行的开头。现在,当我在文件开头正确定位时,我只提取日期和时间(以毫秒计) "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.444“,”yyyy dd HH.mm.ss.zzz");然后一切都好。
我的QString有什么问题呢?我需要追加到strMyDateTime中"\0“,还是需要其他转换??
发布于 2011-09-30 23:05:24
您的字符串有额外的字符,最有可能是开头的空格。您的格式字符串是23个字符,您使用的是左(24),所以必须有一个额外的字符。你在评论朱的答案时说,更改24到23会使最后一个毫秒的字符下降,所以额外的字符必须在开头。
发布于 2011-09-30 21:43:43
"2011-03-03 03.33.13.444"实际上有23个字符长,而不是24个字符。您提取的字符串可能在末尾有一个额外的字符?
https://stackoverflow.com/questions/7616263
复制相似问题