Saturday, January 28, 2012

Converting UTC DateTime to local timezone in WP7

I'm currently using the following to convert a DataTime know to be in NZST to NZDT when applicable. I.e. The code will automatically determine if daylight savings should be applied.

    public static DateTime DateTimeFromNzst(DateTime nzstDateTime)
    {
        // Known offset from UTC
        TimeSpan nzstOffset = new TimeSpan(12, 0, 0);
        DateTimeOffset dateTimeOffset = new DateTimeOffset(nzstDateTime, nzstOffset);
        DateTimeOffset dateTimeOffsetConvertedToLocal = TimeZoneInfo.ConvertTime(dateTimeOffset, TimeZoneInfo.Local);
        return dateTimeOffsetConvertedToLocal.DateTime;
    }

It should also be possible to convert from UTC to the local timezone by adjusting the known UTC offset to 0.

    public static DateTime DateTimeFromUtc(DateTime utcDateTime)
    {
        // Known offset from UTC
        TimeSpan utcOffset = new TimeSpan();
        DateTimeOffset dateTimeOffset = new DateTimeOffset(utcDateTime, utcOffset);
        DateTimeOffset dateTimeOffsetConvertedToLocal = TimeZoneInfo.ConvertTime(dateTimeOffset, TimeZoneInfo.Local);
        return dateTimeOffsetConvertedToLocal.DateTime;
    }