Qt字符串转时间

Qt字符串转时间本地语言问题

问题

最近写了个解析git日志生成周报的“小”程序,需要解析git时间。

由于对git命令不太熟,决定采用QDateTime :: fromString() 转时间,但是该函数返回了空值。

百度了半天也没找到答案,我想可能大家是没我这么粗心吧。。。

代码如下:

1
2
3
4
5
6
7
8

QString gitCmd = "git log master"; //过滤条件未写
QProcess p(this);
p.start("cmd", QStringList() << "/c" << gitCmd);
p.waitForStarted();
p.waitForFinished();
QString result = p.readAllStandardOutput();

result中的时间格式为Sun May 9 17:19:49 2021 +0800

只考虑+0800前面的部分Sun May 9 17:19:49 2021

查阅Qt assistant,发现可以采用如下代码将其转为QDateTime

1
2
3
QString timeString("Sun May 9 17:19:49 2021");
QDateTime time = QDateTime::fromString(timeString, "ddd MMM d hh:mm:ss yyyy");
qDebug() << time.toString("yyyyMMdd");

发现qDebug()输出为空。

仔细查看Qt assistant, 发现QDateTime::fromString有如下的Note:

Note: Unlike the other version of this function, day and month names must be given in the user’s local language. It is only possible to use the English names if the user’s language is English.

原来是要使用本地语言才可以得到正确结果,所以需要形如周日 5月 23 20:17:39 2021的字符串才可以。

解决方法

使用QLocale::toDateTime()

1
2
3
4
QString timeString("Sun May 9 17:19:49 2021");
QLocale loc(QLocale::English);
QDateTime dateTime = loc.toDateTime(timeString, "ddd MMM d hh:mm:ss yyyy");
qDebug() << dateTime.toString("yyyyMMdd");

使用git命令格式化时间字符串

由于对git命令不熟,git官网Git - 查看提交历史 (git-scm.com)也没有详细介绍如果格式化时间字符串, 而且加上时间格式化语句还出现了其他过滤条件不起作用的问题,所以开始时一心想着用代码去解决该问题,后来发现还是直接用命令格式化最简单:

1
2
3
QString gitCmd = "git log master"; //过滤条件未写
const QString logDateFormat = " --date=format:%Y-%m-%d-%H-%M-%S ";
gitCmd += logDateFormat;

如果还有其他过滤条件,应该将其放到logDateFormat前,否则可能导致过滤条件不起作用的问题。

总结

  1. Qt最好的资料还是 Qt assistant, 百度半天不如耐心看文档。

参考