Establecer System Time Zone desde .NET

¿Alguien tiene algún código que tomará un campo TimeZoneInfo de .NET y ejecutará el código de interoperabilidad para configurar el huso horario del sistema a través de SetTimeZoneInformation? Me doy cuenta de que básicamente está mapeando los miembros de TimeZoneInfo a los miembros de la estructura, pero no me parece obvio cómo los campos se correlacionarán exactamente o lo que me debería importar más allá del sesgo.

No sé si esto es lo que está buscando, pero hay información sobre cómo usar las funciones de Win32 para obtener y establecer la información de la zona horaria en

http://www.pinvoke.net/default.aspx/kernel32/GetTimeZoneInformation.html

La parte principal del siguiente código de ejemplo se toma de este sitio. Acabo de agregar algunas líneas más para llamar realmente al método GetTimeZone () y solucioné un pequeño error en el modificador de acceso de la estructura SystemTime para que la muestra funcione.

Espero que esto ayude…

using System; using System.Runtime.InteropServices; namespace Stackoverflow { class TimeZoneFunctionality { ///  /// [Win32 API call] /// The GetTimeZoneInformation function retrieves the current time-zone parameters. /// These parameters control the translations between Coordinated Universal Time (UTC) /// and local time. ///  /// [out] Pointer to a TIME_ZONE_INFORMATION structure to receive the current time-zone parameters. ///  /// If the function succeeds, the return value is one of the following values. ///  ///  /// Return code/value /// Description ///  ///  /// TIME_ZONE_ID_UNKNOWN == 0 ///  /// The system cannot determine the current time zone. This error is also returned if you call the SetTimeZoneInformation function and supply the bias values but no transition dates. /// This value is returned if daylight saving time is not used in the current time zone, because there are no transition dates. ///  ///  ///  /// TIME_ZONE_ID_STANDARD == 1 ///  /// The system is operating in the range covered by the StandardDate member of the TIME_ZONE_INFORMATION structure. ///  ///  ///  /// TIME_ZONE_ID_DAYLIGHT == 2 ///  /// The system is operating in the range covered by the DaylightDate member of the TIME_ZONE_INFORMATION structure. ///  ///  ///  /// If the function fails, the return value is TIME_ZONE_ID_INVALID. To get extended error information, call GetLastError. ///  [DllImport( "kernel32.dll", CharSet = CharSet.Auto )] private static extern int GetTimeZoneInformation( out TimeZoneInformation lpTimeZoneInformation ); ///  /// [Win32 API call] /// The SetTimeZoneInformation function sets the current time-zone parameters. /// These parameters control translations from Coordinated Universal Time (UTC) /// to local time. ///  /// [in] Pointer to a TIME_ZONE_INFORMATION structure that contains the time-zone parameters to set. ///  /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. ///  [DllImport( "kernel32.dll", CharSet = CharSet.Auto )] private static extern bool SetTimeZoneInformation( [In] ref TimeZoneInformation lpTimeZoneInformation ); ///  /// The SystemTime structure represents a date and time using individual members /// for the month, day, year, weekday, hour, minute, second, and millisecond. ///  [StructLayoutAttribute( LayoutKind.Sequential )] public struct SystemTime { public short year; public short month; public short dayOfWeek; public short day; public short hour; public short minute; public short second; public short milliseconds; } ///  /// The TimeZoneInformation structure specifies information specific to the time zone. ///  [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )] public struct TimeZoneInformation { ///  /// Current bias for local time translation on this computer, in minutes. The bias is the difference, in minutes, between Coordinated Universal Time (UTC) and local time. All translations between UTC and local time are based on the following formula: /// UTC = local time + bias /// This member is required. ///  public int bias; ///  /// Pointer to a null-terminated string associated with standard time. For example, "EST" could indicate Eastern Standard Time. The string will be returned unchanged by the GetTimeZoneInformation function. This string can be empty. ///  [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 32 )] public string standardName; ///  /// A SystemTime structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. If the time zone does not support daylight saving time or if the caller needs to disable daylight saving time, the wMonth member in the SystemTime structure must be zero. If this date is specified, the DaylightDate value in the TimeZoneInformation structure must also be specified. Otherwise, the system assumes the time zone data is invalid and no changes will be applied. /// To select the correct day in the month, set the wYear member to zero, the wHour and wMinute members to the transition time, the wDayOfWeek member to the appropriate weekday, and the wDay member to indicate the occurence of the day of the week within the month (first through fifth). /// Using this notation, specify the 2:00a.m. on the first Sunday in April as follows: wHour = 2, wMonth = 4, wDayOfWeek = 0, wDay = 1. Specify 2:00a.m. on the last Thursday in October as follows: wHour = 2, wMonth = 10, wDayOfWeek = 4, wDay = 5. ///  public SystemTime standardDate; ///  /// Bias value to be used during local time translations that occur during standard time. This member is ignored if a value for the StandardDate member is not supplied. /// This value is added to the value of the Bias member to form the bias used during standard time. In most time zones, the value of this member is zero. ///  public int standardBias; ///  /// Pointer to a null-terminated string associated with daylight saving time. For example, "PDT" could indicate Pacific Daylight Time. The string will be returned unchanged by the GetTimeZoneInformation function. This string can be empty. ///  [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 32 )] public string daylightName; ///  /// A SystemTime structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this operating system. If the time zone does not support daylight saving time or if the caller needs to disable daylight saving time, the wMonth member in the SystemTime structure must be zero. If this date is specified, the StandardDate value in the TimeZoneInformation structure must also be specified. Otherwise, the system assumes the time zone data is invalid and no changes will be applied. /// To select the correct day in the month, set the wYear member to zero, the wHour and wMinute members to the transition time, the wDayOfWeek member to the appropriate weekday, and the wDay member to indicate the occurence of the day of the week within the month (first through fifth). ///  public SystemTime daylightDate; ///  /// Bias value to be used during local time translations that occur during daylight saving time. This member is ignored if a value for the DaylightDate member is not supplied. /// This value is added to the value of the Bias member to form the bias used during daylight saving time. In most time zones, the value of this member is –60. ///  public int daylightBias; } ///  /// Sets new time-zone information for the local system. ///  /// Struct containing the time-zone parameters to set. public static void SetTimeZone( TimeZoneInformation tzi ) { // set local system timezone SetTimeZoneInformation( ref tzi ); } ///  /// Gets current timezone information for the local system. ///  /// Struct containing the current time-zone parameters. public static TimeZoneInformation GetTimeZone() { // create struct instance TimeZoneInformation tzi; // retrieve timezone info int currentTimeZone = GetTimeZoneInformation( out tzi ); return tzi; } ///  /// Oversimplyfied method to test the GetTimeZone functionality ///  /// the usual stuff static void Main( string[] args ) { TimeZoneInformation timeZoneInformation = GetTimeZone(); return; } } } 

Antes de configurar la información de la zona horaria, deberá asegurarse de que el proceso tenga los privilegios adecuados. Como se indica en la página de MSDN para SetTimeZoneInformation:

Una aplicación debe tener el privilegio SE_TIME_ZONE_NAME para que esta función tenga éxito. Este privilegio está deshabilitado por defecto.

Aquí hay un código de muestra para habilitar este privilegio:

 public class AdjustTokenPrivilegesFunctionality { [StructLayout(LayoutKind.Sequential)] private struct LUID { public uint LowPart; public int HighPart; } [StructLayout(LayoutKind.Sequential)] private struct LUID_AND_ATTRIBUTES { public LUID Luid; public UInt32 Attributes; } private struct TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public LUID_AND_ATTRIBUTES[] Privileges; } public const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"; public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; public const int TOKEN_QUERY = 0x00000008; public const int SE_PRIVILEGE_ENABLED = 0x00000002; [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, UInt32 Zero, IntPtr Null1, IntPtr Null2); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, out IntPtr tokenhandle); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern int GetCurrentProcess(); [DllImport("advapi32.dll", CharSet = CharSet.Auto)] private static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid); static void EnableSetTimeZonePrivileges() { // We must add the set timezone privilege to the process token or SetTimeZoneInformation will fail IntPtr token; int retval = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out token); Assert.IsTrue(retval != 0, String.Format("OpenProcessToken failed. GetLastError: {0}", Marshal.GetLastWin32Error())); LUID luid = new LUID(); retval = LookupPrivilegeValue(null, SE_TIME_ZONE_NAME, ref luid); Assert.IsTrue(retval != 0, String.Format("LookupPrivilegeValue failed. GetLastError: {0}", Marshal.GetLastWin32Error())); TOKEN_PRIVILEGES tokenPrivs = new TOKEN_PRIVILEGES(); tokenPrivs.PrivilegeCount = 1; tokenPrivs.Privileges = new LUID_AND_ATTRIBUTES[1]; tokenPrivs.Privileges[0].Luid = luid; tokenPrivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; Assert.IsTrue(AdjustTokenPrivileges(token, false, ref tokenPrivs, 0, IntPtr.Zero, IntPtr.Zero), String.Format("AdjustTokenPrivileges failed. GetLastError: {0}", Marshal.GetLastWin32Error())); } } 

Hay otra manera de hacer esto, que ciertamente es un truco, pero que funciona bastante bien en la práctica:

 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(); } } 

Simplemente llame a este método y pase el TimeZoneInfo.Id que desea establecer. Por ejemplo:

 SetSystemTimeZone("Eastern Standard Time"); 

No se requieren privilegios especiales para ejecutar este código, ya que tzutil.exe ya tiene los permisos apropiados.

Hay un artículo para hacer esto usando VB en el sitio de soporte de Microsoft:

Cómo cambiar la información de zona horaria mediante Visual Basic