【问题标题】:Issue with QDateTime (currentDateTime() and fromString())QDateTime 问题(currentDateTime() 和 fromString())
【发布时间】:2014-10-14 14:57:37
【问题描述】:

我已经尝试在我的程序中使用 QDateTime 有一段时间了,但没有这样的运气。我不确定我做错了什么,这让我有点生气。

代码sn-p如下:

QDateTime dteNow = QDateTime::currentDateTime();
QDateTime dteStart = QDateTime::fromString(QString::fromStdString(advertSchedule.ValidFrom),"yyyy-MM-dd hh:mm:ss"); //ValidFrom = "1990-01-01 00:00:00"
QDateTime dteFinish = QDateTime::fromString(QString::fromStdString(advertSchedule.ValidTo),"yyyy-MM-dd hh:mm:ss"); //ValidTo = "2015-01-01 00:00:00"

//Breakpointed on the line below. Continuing to run causes an exception. 
//Hovering over the QDateTime objects displays "dteNow (invalid) QDateTime".
if(dteNow >= dteStart
    && dteNow < dteFinish
    && dteNow.time() >= dteStart.time()
    && dteNow.time() < dteFinish.time())
{

这三个日期时间在运行时都是无效的。

提前致谢。

【问题讨论】:

  • 您将什么定义为“运行时无效”?让我们只关注 QDateTime::currentDateTime()。如果打印 QDateTime::currentDateTime().toString(Qt::TextDate) 会得到什么?
  • 我什么也没得到,它什么也没输出。在运行时,我的意思是我在这三行之后设置了断点,并且将鼠标悬停在它们上面都表明它们都是无效的。
  • 你能发布代码的上下文吗? QDateTime 对象会超出范围吗?忽略调试器所说的内容并将文本输出到控制台。
  • 我已经编辑了代码 sn-p。我希望它有所帮助。
  • 来自 QDateTime::fromStdString 的文档“使用给定的格式返回由字符串表示的 QDateTime,如果不可能,则返回无效的日期时间。”我预计格式错误并且您得到的字符串无效,因此调用 .time 会触发异常。

标签: c++ qt qdatetime


【解决方案1】:

由于在 QDateTime 上调用 .time() 时会引发异常,因此一个或多个 QDateTime 对象无效。

我建议你分解以下几行:-

QDateTime::fromString(QString::fromStdString(advertSchedule.ValidFrom),"yyyy-MM-dd hh:mm:ss");
QDateTime dteFinish = QDateTime::fromString(QString::fromStdString(advertSchedule.ValidTo),"yyyy-MM-dd hh:mm:ss"); 

检查调用 QString::fromStdString(advertSchedule.ValidFrom) 和 QString::fromStdString(advertSchedule.ValidTo) 时返回的内容。

也试试以下方法:-

QDateTime dteNow = QDateTime::currentDateTime();
if(dteNow.isValid())
{
    qDebug("The date is valid: %s\n", dteNow.toString());
}
else
{
    qDebug("The current date returned is invalid\n");
}

如果在“应用程序输出”窗口(或控制台,如果您从那里运行)中显示日期无效,请清理项目并重新构建。

【讨论】:

  • 我已经清理并重建了我的项目,但仍然没有这样的运气。为什么 QDateTime::currentDateTime() 返回无效的 QDateTime?
  • 你在什么平台上运行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 2023-04-07
相关资源
最近更新 更多