Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set System Time Zone from .NET

Does anyone have some code that will take a TimeZoneInfo field from .NET and execute the interop code to set the system time zone via SetTimeZoneInformation? I realize that it's basically mapping the TimeZoneInfo members to the struct members, but it does not appear obvious to me how the fields will map exactly or what I should care about beyond the bias.

like image 755
user19297 Avatar asked Apr 30 '09 19:04

user19297


People also ask

Does C# DateTime have a TimeZone?

DateTime itself contains no real timezone information.

What is TimeZone in C#?

C# TimeZone ExamplesUse the TimeZone type, which is a class in the System namespace that represents different time zones. TimeZone. This C# type, part of System, describes the current time zone. It gets information about the time zone of the current computer. Notes, time zones.


1 Answers

There's another way to do this, which admittedly is a bit of a hack, but works quite well in practice:

public void SetSystemTimeZone(string timeZoneId)
{
    var process = Process.Start(new ProcessStartInfo
    {
        FileName = "tzutil.exe",
        Arguments = "/s \"" + timeZoneId + "\"",
        UseShellExecute = false,
        CreateNoWindow = true
    });

    if (process != null)
    {
        process.WaitForExit();
        TimeZoneInfo.ClearCachedData();
    }
}

Simply call this method and pass the TimeZoneInfo.Id that you wish to set. For example:

SetSystemTimeZone("Eastern Standard Time");

No special privileges are required to run this code, as tzutil.exe already has the appropriate permissions.

like image 195
Matt Johnson-Pint Avatar answered Oct 06 '22 18:10

Matt Johnson-Pint