C++/Cx: Getting around the very limited DateTime object

You know, I have been writing a LOT of C++/Cx recently and I have hit a bunch of issues. This particular one is about the DateTime object in C++/Cx. If you look at the C# version of the DateTime object, it contains a ton of niceties. There are properties that will give you the Day, Hour, Minute, Seconds, add time to it, remove time to it… I guess you get the point. So, when I had to do some similar operations in C++/Cx, I typed DateTime-> and waited for intellisense to show me all the properties. Unfortunately, all it showed me was a single member called UniversalTime!! I looked a bit deeper and I realized all you get is a 64 bit signed integer which represents time in 100 nanoseconds interval. I almost bit my lip in frustration as I felt like I have gone back to the era of Win32 and FILETIME. Especially so, since the documentation very helpfully suggests that the DateTime.UniversalTime has the same granularity as the FILETIME

After much searching, I finally found something that saved the day. Ta-Da! Here is the well kept secret courtesy the following support page. What you really need is the Windows::Globalization::Calendar class where you can set the value to whatever DateTime you want by using Calendar::SetDateTime. You can do whatever manipulations you want on the calendar object and then finally get a DateTime object back from the calendar. For instance, if you just wanted to get the current time and add a few seconds to it, you could do the following:

1
2
3
4
5
Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
int expiresInSeconds = 20;
calendar->SetToNow();
calendar->AddSeconds(expiresInSeconds);
DateTime myDateTime = calendar->GetDateTime();

One more problem I faced was that I needed to get the max value of DateTime. I could have calculated it but that is way too much work. This works just fabulous:

1
2
3
Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
calendar->SetToMax();
DateTime myDateTime = calendar->GetDateTime();

In short, DateTime seems like a structure, that one should wrap up in the Calendar object as soon as possible, do all the manipulations on the calendar and convert back to DateTime as needed.

Cheers

Leave a comment

Your email address will not be published. Required fields are marked *