Setting Alarms on Android

Setting Alarms on Android

Setting alarms on Android using the AlarmManager is not straightforward for .Net folk because the alarm Date/Time is not expressed by something similar to the .Net DateTime structure but rather by a value of type “long” that represents the time, in milliseconds, since the Unix epoch (January 1, 1970 @ 00:00:00 UTC).

So to convert a local DateTime member to AlarmManager milliseconds use the following code:

...

private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

...

/// <summary>
/// Converts DateTime to Unix epoch milliseconds (what Android AlarmManager expects)
/// </summary>
public static long ToEpochMilliseconds(DateTime dateTime)
{
    if (dateTime.Kind == DateTimeKind.Unspecified)
        dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); // or Local - be careful

    return (long)(dateTime.ToUniversalTime() - UnixEpoch).TotalMilliseconds;
}