7

我试图在一个时区中看到所有偏移量,在一个时间间隔内。下面是我用来完成此操作的函数,我知道您可以在标准时间使用TimeZoneInfo.BaseUtcOffset获取UTC offset时区,但是在夏令时没有类似的方法来获取时区,除非您将特定DST时间点传递给该GetUTCOffset()方法.

static void GetOffsets(DateTime startTime, DateTime endTime, TimeZoneInfo tz)
{
    var result = new HashSet<int>();
    var adjRules = tz.GetAdjustmentRules();
    result.Add(tz.BaseUtcOffset);

    foreach (var adjustmentRule in adjRules)
    {
        if ((startTime >= adjustmentRule.DateStart && startTime <= adjustmentRule.DateEnd) || (endTime >= adjustmentRule.DateStart && endTime <= adjustmentRule.DateEnd) ||
             (stTime <= adjustmentRule.DateStart && endTime >= adjustmentRule.DateEnd))
        {
            if(adjustmentRule.DaylightDelta != TimeSpan.Zero)
            {
                if (!result.Contains(tz.BaseUtcOffset + adjustmentRule.DaylightDelta))
                      result.Add((tz.BaseUtcOffset + adjustmentRule.DaylightDelta));
            }
         }
     }

     foreach (var res in result)
     {
         Console.WriteLine(res);
     }
}

请让我知道是否有更好的方法来做到这一点。

4

3 回答 3

6

我试图在一个时区中看到所有偏移量,在一个时间间隔内。

强烈建议您避免尝试TimeZoneInfo直接使用。在某些年份,某些区域的调整规则可能会令人惊讶地尴尬,正如我发现的那样。

虽然我有偏见,但我建议使用Noda Time,它可以包装 aTimeZoneInfo并通过BclDateTimeZone.FromTimeZoneInfo. 您的问题在要求方面并不完全清楚,但是如果您可以多说一点您要做什么,我可以为您编写适当的 Noda Time 代码。

您的初始描述可以通过以下方式实现:

public IEnumerable<ZoneInterval> GetZoneIntervalsInInterval
    (this DateTimeZone zone, Interval interval)
{
    Instant current = interval.Start;
    while (current < interval.End && current != Instant.MaxValue)
    {
        ZoneInterval zi = zone.GetZoneInterval(current);
        yield return zi;
        current = zi.End;
    }
}

然后:

var zone = BclDateTimeZone.FromTimeZoneInfo(tzInfo);
var offsets = zone.GetZoneIntervalsInInterval(interval)
                  .Select(zi => zi.WallOffset)
                  .Distinct();

那是假设您与我所说的“偏移量”意思相同(即UTC与本地时间之间的差异)。

于 2012-11-13T15:34:12.903 回答
0

我确实想出了这种方法来获取指定时区信息的一年间隔内的UTC间隔需要考虑的偏移量。我将此集合传递给数据库以过滤保存在 UTC 中的日期时间字段,以获取间隔过滤器输入,例如(“1am - 2am”),我确实为我系统中的所有时区测试了这个,它工作正常。虽然这不是我最初问题的答案,因为我仍在使用调整规则来获取偏移量,但这次我试图让它可用。

class Program
{
    static void Main(string[] args)
    {
        foreach (var tz in TimeZoneInfo.GetSystemTimeZones())
        {
            var result = GetUTCOffsetsByUTCIntervals(1900, 2012, tz);
            Console.WriteLine(tz.DisplayName);
            foreach (var tuple in result)
            {
                Console.WriteLine(tuple.Item1 + "     " + tuple.Item2 + "   " + tuple.Item3);
            }
            Console.WriteLine("------------------------------------------------------------");
        }
        Console.Read();
    }

    public static List<Tuple<TimeSpan, DateTime, DateTime>> GetUTCOffsetsByUTCIntervals(int stYear, int endYear, TimeZoneInfo tz)
    {
        var cal = CultureInfo.CurrentCulture.Calendar;
        var offsetsByUTCIntervals = new List<Tuple<TimeSpan, DateTime, DateTime>>();
        var adjRules = tz.GetAdjustmentRules();
        for (var year = stYear; year <= endYear && year < DateTime.MaxValue.Year && year >= DateTime.MinValue.Year; year++)
        {
            var adjRule =
                adjRules.FirstOrDefault(
                    rule =>
                    rule.DateStart.Year == year || rule.DateEnd.Year == year ||
                    (rule.DateStart.Year < year && rule.DateEnd.Year > year));

            var yrStTime = new DateTime(year, 1, 1);
            var yrEndTime = yrStTime.AddYears(1).AddTicks(-1);

            if (adjRule != null)
            {
                var tStDate = GetTransitionDate(adjRule.DaylightTransitionStart, year);
                var tEnddate = GetTransitionDate(adjRule.DaylightTransitionEnd, year);

                var stTsp = adjRule.DaylightTransitionStart.TimeOfDay.TimeOfDay;

                var endTsp = adjRule.DaylightTransitionEnd.TimeOfDay.TimeOfDay;

                if (yrStTime.Date == tStDate && yrStTime.TimeOfDay == stTsp)
                    yrStTime = yrStTime.Add(adjRule.DaylightDelta);

                if (yrEndTime.Date == tEnddate && yrEndTime.TimeOfDay == endTsp)
                    yrEndTime = yrEndTime.Subtract(adjRule.DaylightDelta);

              if (tStDate.Month > tEnddate.Month)
                {
                    offsetsByUTCIntervals.Add(new Tuple<TimeSpan, DateTime, DateTime>(tz.BaseUtcOffset + adjRule.DaylightDelta, ConvertTimeToUtc(yrStTime, tz), ConvertTimeToUtc(tEnddate.AddTicks(endTsp.Ticks - 1), tz)));
                    offsetsByUTCIntervals.Add(new Tuple<TimeSpan, DateTime, DateTime>(tz.BaseUtcOffset, ConvertTimeToUtc(tEnddate.Add(endTsp.Subtract(adjRule.DaylightDelta)), tz), ConvertTimeToUtc(tStDate.AddTicks(stTsp.Ticks - 1), tz)));
                    offsetsByUTCIntervals.Add(new Tuple<TimeSpan, DateTime, DateTime>(tz.BaseUtcOffset + adjRule.DaylightDelta, ConvertTimeToUtc(tStDate.Add(stTsp.Add(adjRule.DaylightDelta)), tz), ConvertTimeToUtc(yrEndTime, tz))); 
                }
                else
                {
                    offsetsByUTCIntervals.Add(new Tuple<TimeSpan, DateTime, DateTime>(tz.BaseUtcOffset, ConvertTimeToUtc(yrStTime, tz), ConvertTimeToUtc(tStDate.AddTicks(stTsp.Ticks - 1), tz)));
                    offsetsByUTCIntervals.Add(new Tuple<TimeSpan, DateTime, DateTime>(tz.BaseUtcOffset + adjRule.DaylightDelta, ConvertTimeToUtc(tStDate.Add(stTsp.Add(adjRule.DaylightDelta)), tz), ConvertTimeToUtc(tEnddate.AddTicks(endTsp.Ticks - 1), tz)));
                    offsetsByUTCIntervals.Add(new Tuple<TimeSpan, DateTime, DateTime>(tz.BaseUtcOffset, ConvertTimeToUtc(tEnddate.Add(endTsp.Subtract(adjRule.DaylightDelta)), tz), ConvertTimeToUtc(yrEndTime, tz))); 
                }
            }
            else
            {
                offsetsByUTCIntervals.Add(new Tuple<TimeSpan, DateTime, DateTime>(tz.BaseUtcOffset, ConvertTimeToUtc(yrStTime, tz), ConvertTimeToUtc(yrEndTime, tz)));
            }
        }
        return offsetsByUTCIntervals;
    }

    public static DateTime ConvertTimeToUtc(DateTime date, TimeZoneInfo timeZone)
    {
        if (date == null || timeZone == null)
        {
            return date;
        }
        DateTime convertedDate = TimeZoneInfo.ConvertTimeToUtc(date, timeZone);
        return convertedDate;
    }

    //copy from msdn http://msdn.microsoft.com/en-us/library/system.timezoneinfo.transitiontime.isfixeddaterule.aspx
    private static DateTime GetTransitionDate(TimeZoneInfo.TransitionTime transition, int year)
    {
        if (transition.IsFixedDateRule)
            return new DateTime(year, transition.Month, transition.Day);

        int transitionDay;
        var cal = CultureInfo.CurrentCulture.Calendar;
        var startOfWeek = transition.Week * 7 - 6;
        var firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transition.Month, 1));
        var changeDayOfWeek = (int)transition.DayOfWeek;

        if (firstDayOfWeek <= changeDayOfWeek)
            transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
        else
            transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);

        if (transitionDay > cal.GetDaysInMonth(year, transition.Month))
            transitionDay -= 7;
        return new DateTime(year, transition.Month, transitionDay);
    }

   /* static void GetOffsets(DateTime startTime, DateTime endTime, TimeZoneInfo tz)
    {
        var result = new HashSet<string>();
        var adjRules = tz.GetAdjustmentRules();
        result.Add(tz.BaseUtcOffset.ToString());

        foreach (var adjustmentRule in adjRules)
        {
            if ((startTime >= adjustmentRule.DateStart && startTime <= adjustmentRule.DateEnd)
                    || (endTime >= adjustmentRule.DateStart && endTime <= adjustmentRule.DateEnd)
                 || (startTime <= adjustmentRule.DateStart && endTime >= adjustmentRule.DateEnd))
            {
                if(adjustmentRule.DaylightDelta != TimeSpan.Zero)
                {
                    if (!result.Contains((tz.BaseUtcOffset + adjustmentRule.DaylightDelta).ToString()))
                      result.Add((tz.BaseUtcOffset + adjustmentRule.DaylightDelta).ToString());
                }
            }
        }
        Console.Write(tz.DisplayName + "   ");
        foreach (var res in result)
        {
            Console.Write(res);
        }
    }*/
}
于 2012-11-13T15:04:09.180 回答
-1

如果你对日期做任何复杂的事情,你应该看看Noda Time(它是 Joda Time Java 库的一个端口)。它有一个完整的命名空间来处理棘手的时区问题。

于 2012-11-11T03:36:54.000 回答