Skip to content

Get Better Dates with the New Xojo Framework

Time zones can cause confusion even for super villains. But the Xojo framework has got you covered, whether you are out to do good or evil.

If you’ve written code for long enough, you’ve probably had bugs where you failed to consider some of the differences between two dates.

Consider the following Classic Xojo framework example that adds 3 hours to a specific date:

Dim d As New Date(2017, 11, 5)
d.Hour = d.Hour + 3
MsgBox(Str(d))

Easy enough, right? Unfortunately, while code like this will provide the correct result most of the time, it won’t this time because on November 5th, 2017 here in the United States, Daylight Savings ends. As a result, the value return will be off by an hour.

API 2.0 solves this problem by introducing the DateTime and DateInterval classes which is used to add or subtract time and takes into account time zones:

Var d As New DateTime(2017, 11, 5, 0, 0, 0, 0, TimeZone.Current)
Var di As New DateInterval(0, 0, 0, 3)
d = d + di
MessageBox(d.ToString)

This example creates a new date and provides the current time zone then creates a DateInterval and assigns it 3 hours. The DateInterval is then added to the date and the result displayed. This code will always be correct because time zones are being considered. This one is pretty straightforward because it’s only dealing with US Daylight Savings Time but imagine if one date was tied to someone in the US and another to someone in Europe. Not only do you have different time zones but Daylight Savings Time starts and stops on different dates between the US and Europe. The new DateTime and DateInterval classes in API 2.0 handle all of that complexity for you. Because the new DateTime class understands time zones, using TimeZone.Current for example, means you don’t even have to think about it at all. Your calculations will just work no matter where the user is in the world.

The API 2.0 solution requires one extra line of code. However, that one extra line gets you code that will always produce the correct result. The Date class in the Classic Xojo framework will be right most of the time but when it’s wrong, you may wrack your brain for a while trying to figure out why. That extra line of code is worth every keystroke.

This example deals only with time zones but the DateTime and DateInterval classes also handle leap years for you as well. That’s another example where it would be very easy to miss the fact that a leap year occurred and get the wrong result.

The changes to date and time handling in API 2.0 are just a few examples of why we have created it and why it’s worth your time to start using it.

Note: This post was updated for API 2.0 on June 15th, 2020.