## Time difference

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
danielNS
Earned a small fee
Posts: 12
Joined: Tue Dec 27, 2011 12:45 pm

### Time difference

How can I get the difference (in milliseconds) between two wxDateTime values?

t1 and t2 are to different times separated (at most) by less than 10 seconds.

I got t1 and t2 by using wxDateTime::Now();

I tried this code, but it doesn't work well:

Code: Select all

``````int msecdif(wxDateTime t2, wxDateTime t1)
{
int h1,h2,m1,m2,s1,s2,ms1,ms2;
h1=t1.GetHour();m1=t1.GetMinute();s1=t1.GetSecond();ms1=t1.GetMillisecond();
h2=t2.GetHour();m2=t2.GetMinute();s2=t2.GetSecond();ms2=t2.GetMillisecond();
if (h1!=h2) m2=m2+60;
if (m1!=m2) s2=s2+60;
if (s1!=s2) ms2=ms2+ ((s2-s1)*1000);
return ms2-ms1;
}``````
Debian - GCC - WX 3.1 - Code::Blocks

DenDev
Filthy Rich wx Solver
Posts: 223
Joined: Mon Jan 19, 2015 1:45 pm

### Re: Time difference

Try this:

Code: Select all

``````int64_t wxDateTimeToMillis(wxDateTime dt)
{
int64_t res = dt.GetHour() * 60;
res = (res + dt.GetMinute()) * 60;
return ((res + dt.GetSecond()) * 1000) + dt.GetMillisecond();
}

int64_t DifferenceInMillis(wxDateTime t1, wxDateTime t2)
{
return wxDateTimeToMillis(t1) - wxDateTimeToMillis(t2);
}``````
I have a bad habbit of not testing the code I post

doublemax
Moderator
Posts: 13903
Joined: Fri Apr 21, 2006 8:03 pm
Location: \$FCE2

### Re: Time difference

Code: Select all

``````wxLongLong msecdif(wxDateTime t2, wxDateTime t1)
{
return t2.Subtract( t1 ).GetMilliseconds();
}
``````
If you know the time difference fits in a 32 bit value, you can truncate the result

Code: Select all

``````long msecdif(wxDateTime t2, wxDateTime t1)
{
return t2.Subtract( t1 ).GetMilliseconds().ToLong();
}
``````
This is the method you probably missed:
http://docs.wxwidgets.org/trunk/classwx ... 75eac4beea
Use the source, Luke!

danielNS
Earned a small fee
Posts: 12
Joined: Tue Dec 27, 2011 12:45 pm