[Qt-interest] How calculate time span (days, hours, minutes) QDateTime difference?

Reece Dunn msclrhd at googlemail.com
Fri Jun 11 20:54:27 CEST 2010


On 11 June 2010 18:49, Sean Harmer <sean.harmer at maps-technology.com> wrote:
> Hi,
>
> On Friday 11 June 2010 16:58:08 Ed Sutton wrote:
>> >http://doc.trolltech.com/4.6/qdatetime.html#secsTo
>> >
>> >gives you seconds.
>> >
>> >The rest is trivial.
>>
>> Thank you Dan and Jason.
>>
>> QDateTime::secsTo() does the trick with some additional work.
>>
>> I was hoping I had missed the Qt equivalent of the .NET TimeSpan structure.
>>
>> http://msdn.microsoft.com/en-us/library/system.timespan.aspx
>
> Yes I have been thinking about adding something like this for a while now.
> Maybe I will try to put a merge request together on gitorious for such a
> class.
>
> Does anybody have any other features that they would like for such a class?

I have an application (text-to-speech) where I know the percentage of
the document read, but not the played and total time. I am deriving
these using the following code:

static QString formatTime(double seconds)
{
	double minutes = floor(seconds / 60.0);
	seconds = seconds - (minutes * 60.0);

	double hours = floor(minutes / 60.0);
	minutes = minutes - (hours * 60.0);

	char time[80];
	sprintf(time, "%02.0f:%02.0f:%02.0f", hours, minutes, seconds);

	return time;
}

void progressChanged(float progress)
{
	if (m_start_time == 0)
	{
		m_start_time = time(NULL);
		m_start_progress = progress / 100.0f;
	}
	else
	{
		float current_progress = progress / 100.0f;

		double elapsed_time = difftime(time(NULL), m_start_time);
		double total_time = elapsed_time / (current_progress - m_start_progress);
		double played_time = total_time * current_progress;

		m_progress->setText(i18nc("@info:status", "%1 of %2 (%3%)")
			.arg(formatTime(played_time))
			.arg(formatTime(total_time))
			.arg(progress, 5, 'f', 2, '0'));
	}
}

It would be great if there was an easier way to do this using Qt classes, e.g.:

	if (!m_start_time.isValid())
	{
		m_start_time = QDateTime::now();
		m_start_progress = progress / 100.0f;
	}
	else
	{
		float current_progress = progress / 100.0f;

		QTimeSpan elapsed_time = QDateTime::now() - m_start_time;
		QTimeSpan total_time = elapsed_time / (current_progress - m_start_progress);
		QTimeSpan played_time = total_time * current_progress;

		m_progress->setText(i18nc("@info:status", "%1 of %2 (%3%)")
			.arg(played_time.format("%H:%M:%S"))
			.arg(total_time.format("%H:%M:%S"))
			.arg(progress, 5, 'f', 2, '0'));
	}

- Reece



More information about the Qt-interest-old mailing list