Pregunta

Tengo problemas para comprender cómo el Registro del sistema puede ayudarme a convertir un objeto DateTime en la TimeZone correspondiente. Tengo un ejemplo de que he estado tratando de realizar ingeniería inversa, pero no puedo seguir el único paso crítico en el que el horario UTC se compensa en función del horario de verano.

Estoy usando .NET 3.5 (gracias a Dios) pero todavía me desconcierta.

Gracias

EDITAR: Información adicional: Esta pregunta fue para usar en un entorno de aplicación WPF. El fragmento de código que dejé a continuación llevó el ejemplo de respuesta un paso más allá para obtener exactamente lo que estaba buscando.

¿Fue útil?

Solución

Aquí hay un fragmento de código en C # que estoy usando en mi aplicación WPF. Esto le dará la hora actual (ajustada para el horario de verano) para la identificación de zona horaria que proporcione.

// _timeZoneId is the String value found in the System Registry.
// You can look up the list of TimeZones on your system using this:
// ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones();
// As long as your _timeZoneId string is in the registry 
// the _now DateTime object will contain
// the current time (adjusted for Daylight Savings Time) for that Time Zone.
string _timeZoneId = "Pacific Standard Time";
DateTime startTime = DateTime.UtcNow;
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId);
_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);

Este es el fragmento de código con el que terminé. Gracias por la ayuda.

Otros consejos

Puede usar DateTimeOffset para obtener el desplazamiento UTC, por lo que no debería tener que buscar en el registro esa información.

TimeZone.CurrentTimeZone devuelve datos de zona horaria adicionales, y TimeZoneInfo.Local tiene metadatos sobre la zona horaria (como si admite el horario de verano, los nombres de sus diversos estados, etc.).

Actualización: creo que esto responde específicamente a su pregunta:

var tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);
Console.WriteLine(dto);
Console.ReadLine();

Ese código crea un DateTime con un desplazamiento de -8. Las zonas horarias predeterminadas instaladas son en MSDN .

//C#.NET
    public static bool IsDaylightSavingTime()
    {
        return IsDaylightSavingTime(DateTime.Now);
    }
    public static bool IsDaylightSavingTime(DateTime timeToCheck)
    {
        bool isDST = false;
        System.Globalization.DaylightTime changes 
            = TimeZone.CurrentTimeZone.GetDaylightChanges(timeToCheck.Year);
        if (timeToCheck >= changes.Start && timeToCheck <= changes.End)
        {
            isDST = true;
        }
        return isDST;
    }


'' VB.NET
Const noDate As Date = #1/1/1950#
Public Shared Function IsDaylightSavingTime( _ 
 Optional ByVal timeToCheck As Date = noDate) As Boolean
    Dim isDST As Boolean = False
    If timeToCheck = noDate Then timeToCheck = Date.Now
    Dim changes As DaylightTime = TimeZone.CurrentTimeZone _
         .GetDaylightChanges(timeToCheck.Year)
    If timeToCheck >= changes.Start And timeToCheck <= changes.End Then
        isDST = True
    End If
    Return isDST
End Function
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top