Wednesday, May 8, 2013

Weird behaviour of DateTime.AddMilliseconds() on Windows Phone

I have recently released a Windows Phone App to the store, and it has received fair amount of attention. There has been, however, an annoying bug in the code that I did not have time to investigate closer until now.
The problem is that this piece of code
private static DateTime julianDateToDate(double julianDate)
{
    DateTime dt = new DateTime(1970, 1, 1);
    dt = dt.AddMilliseconds((julianDate + 0.5 - J1970) * msInDay);
    return dt;
}
results in an ArgumentOutOfRangeException if the argument julianDate is NaN (which happens when the app logic fails to calculate various twilight times – they cannot be calculated at all at certain times of year and place).
The weird thing is that the exception gets raised only when run on the emulator. If it is run on a real device, no exception is raised! Luckily it is possible to debug the code when it is running on a device, which revealed the problem.
The simple correction is to modify the method to manually check the argument and raise the exception:
private static DateTime julianDateToDate(double julianDate)
{
    if (double.IsNaN(julianDate))
        throw new ArgumentOutOfRangeException("julianDate");
    DateTime dt = new DateTime(1970, 1, 1);
    dt = dt.AddMilliseconds((julianDate + 0.5 - J1970) * msInDay);
    return dt;
}
The lesson here obviously is: the emulator is not the same thing as the real device. Remember to test your apps on the device as well!

Edit 10.5.2013: corrected the first piece of code to reflect reality!

No comments:

Post a Comment