Well, the problem is, that without restart of the application,
DateTimeOffset.Now
will return the time from the start timezone. I can`t afford restart of mine application, but I still need get the exact time after the timezone was changed.
The possible solution (a bad one, but it works) - is to run a process, that returns a
DateTimeOffset.Now
and that`s all.
See the code of this process:
using System;
using Microsoft.Win32;
namespace DateTimePick
{
class Program
{
static void Main(string[] args)
{
DateTimeOffset offset = DateTimeOffset.Now;
Console.WriteLine(offset.Offset.TotalHours);
}
}
}
Now I`ve got an executable, that prints offset hours as a double.
In my "main" program I add a class, which runs this process each time the system time is changed (thanks to Zoltán Zörgő for his advice).
public class DateTimeExactPicker
{
static TimeSpan currentOffset;
private static string getExactDateTime()
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "DateTimePick.exe";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
public static DateTimeOffset Now
{
get { return new DateTimeOffset(DateTimeOffset.UtcNow.Ticks + currentOffset.Ticks, currentOffset); }
}
static DateTimeExactPicker()
{
SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged);
currentOffset = DateTimeOffset.Now.Offset;
}
static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
double hoursOffset = double.Parse(getExactDateTime());
TimeSpan offset = TimeSpan.FromHours(hoursOffset);
currentOffset = offset;
}
}
Now my test program looks like this:
static void Main(string[] args)
{
while (true)
{
Console.WriteLine(DateTimeExactPicker.Now);
Console.ReadKey();
}
}
The output is:
03.07.2012 12:03:03 +03:00
03.07.2012 12:03:04 +03:00
03.07.2012 12:03:04 +03:00
03.07.2012 12:03:04 +03:00
...after I change the timezone
03.07.2012 15:33:16 +06:30
03.07.2012 15:33:16 +06:30
03.07.2012 15:33:17 +06:30
03.07.2012 15:33:17 +06:30
03.07.2012 15:33:17 +06:30
...now I`ve changed it back
03.07.2012 12:03:29 +03:00
03.07.2012 12:03:29 +03:00
Listening to
TimeChanged
event is a good idea, because running the process each time, I need the exact time value might be too expensive.