Changing the TimeZone value on .NET 2.0 via Reflection
I needed to change the TimeZone value during a TestCase on .NET 2.0 and it works
Ahhh… reflection… heres how to do it
Note: This will not work with earler version of the framework (and Mono) and may change in future .NET releases. Please Unit test this in your own code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace DotNetTimeZoneValue
{
class Program
{
static void Main(string[] args)
{
Type timeZoneType = typeof(TimeZone);
Type currentSystemTimeZoneType = timeZoneType;
Console.WriteLine("Before bodge");
Console.WriteLine("LocalTime:" + TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now));
Console.WriteLine("UTC:" + TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now));
FieldInfo currentTimeZoneFieldOnTimeZone = timeZoneType.GetField("currentTimeZone", BindingFlags.NonPublic | BindingFlags.Static);
TimeZone currentTimeZone = (TimeZone)currentTimeZoneFieldOnTimeZone.GetValue(TimeZone.CurrentTimeZone);
FieldInfo m_ticksOffset = currentTimeZone.GetType().GetField("m_ticksOffset", BindingFlags.NonPublic | BindingFlags.Instance);
long ticksOffset = (long)m_ticksOffset.GetValue(currentTimeZone);
Console.WriteLine(ticksOffset);
m_ticksOffset.SetValue(currentTimeZone, 0);
Console.WriteLine("After bodge");
Console.WriteLine("LocalTime:" + TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now));
Console.WriteLine("UTC:" + TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now));
m_ticksOffset.SetValue(currentTimeZone, ticksOffset);
Console.WriteLine("After setting orig. value");
Console.WriteLine("LocalTime:" + TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now));
Console.WriteLine("UTC:" + TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now));
Console.ReadLine();
}
}
}
technorati tags: .NET, 2.0, reflection, TimeZone, nunit, hacks