C#: Making sure DateTime.Now returns a GMT + 1 time

后端 未结 3 2098
执笔经年
执笔经年 2020-12-28 09:22

I am using DateTime.Now to show something according to today\'s date, and when working locally (Malta, Europe) the times appear correctly (obviously because of

3条回答
  •  隐瞒了意图╮
    2020-12-28 09:41

    It depends on what you mean by "a GMT + 1 timezone". Do you mean permanently UTC+1, or do you mean UTC+1 or UTC+2 depending on DST?

    If you're using .NET 3.5, use TimeZoneInfo to get an appropriate time zone, then use:

    // Store this statically somewhere
    TimeZoneInfo maltaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("...");
    DateTime utc = DateTime.UtcNow;
    DateTime malta = TimeZoneInfo.ConvertTimeFromUtc(utc, maltaTimeZone );
    

    You'll need to work out the system ID for the Malta time zone, but you can do that easily by running this code locally:

    Console.WriteLine(TimeZoneInfo.Local.Id);
    

    Judging by your comments, this bit will be irrelevant, but just for others...

    If you're not using .NET 3.5, you'll need to work out the daylight savings yourself. To be honest, the easiest way to do that is going to be a simple lookup table. Work out the DST changes for the next few years, then write a simple method to return the offset at a particular UTC time with that list hardcoded. You might just want a sorted List with the known changes in, and alternate between 1 and 2 hours until your date is after the last change:

    // Be very careful when building this list, and make sure they're UTC times!
    private static readonly IEnumerable DstChanges = ...;
    
    static DateTime ConvertToLocalTime(DateTime utc)
    {
        int hours = 1; // Or 2, depending on the first entry in your list
        foreach (DateTime dstChange in DstChanges)
        {
            if (utc < dstChange)
            {
                return DateTime.SpecifyKind(utc.AddHours(hours), DateTimeKind.Local);
            }
            hours = 3 - hours; // Alternate between 1 and 2
        }
        throw new ArgumentOutOfRangeException("I don't have enough DST data!");
    }
    

提交回复
热议问题