2011-01-21 6 views
7

System.TimeZoneInfo 개체와 주어진 다음 DST 전환 날짜/시간을 반환하는 C#의 함수를 작성하거나 이미 종료 한 경우 사용하고 싶습니다. 해당 시간대의 특정 "as of"시간. 반환 된 시간은 제공된 시간대 여야합니다. 나는 "동부 표준시"TimeZoneInfo 중 객체를 전달하고, 예를 들어일광 절약 시간 전환이 발생하는 다음 날짜/시간 가져 오기

public DateTime GetNextTransition(DateTime asOfTime, TimeZoneInfo timeZone) 
{ 
    // Implement me! 
} 

/2천11분의 21 일 17 @ : 내가 원하는 기능은이 서명이있는 "asOfTime"등 00, 나는 이것을 기대 3/13/2011 @ 2 : 00을 반환하는 함수.

구조체에는 필요한 모든 정보가 포함되어 있지만 이상적으로 규칙을 실제 날짜로 변환하는 기본 제공 메커니즘이있을 것입니다. 누구든지 어떤 제안이 있습니까?

+0

DST는 동물입니다 ... 대부분의 애리조나 (인디언 보호 구역 DST)는 DST를 존중하지 않습니다. 우리의 시간대는 MST로 유지되므로 우리는 시간을 조정하지 않습니다 ... 반면 Denver는 MDT로 전환하고 시간을 조정한다고 말합니다. –

+0

Noda Time을 사용하여 전환 시간을 얻는 방법은 [this thread] (http://stackoverflow.com/questions/24373618/getting-daylight-savings-time-start-and-end-in-nodatime)를 참조하십시오. – Azimuth

답변

6

이 페이지의 예를 살펴보면 필요한 정보를 얻을 수 있다고 생각합니다. 이

MSDN - TransitionTime

+0

감사합니다. - 게시 한 직후에 발견되었습니다. 작업을 완료하기 위해 코드를 수정했습니다. 일단 내가 좀 더 자신감을 가지고 내 질문에 내 최종 코드를 게시합니다. 부동 날짜 규칙을 실제 날짜로 변환하는 것이 프레임 워크에 의해 노출되지 않는 것은 너무 나쁩니다. –

+3

@StuartLange 지난 4 년 동안 매분마다 코드를 게시하기를 기다렸습니다. 아직도 그것에 종사하고 있니? – Nissim

+0

이 작업을 수행하는 'TransitionTimeToDateTime'이라는 내부 메서드가 있음에 유의하십시오. [.NET 참조 소스] (http://referencesource.microsoft.com/#mscorlib/system/timezoneinfo.cs,8605eb2eb5309ae8)에서 찾을 수 있습니다. –

0

System.TimeZoneInfo.TransitionTime은 과 같은 시간 전환 데이터를 저장할 수있는 구조이며 실제 값을 계산하는 함수가 아닙니다. 이러한 함수를 만들려면 데이터를 어딘가에서 온라인으로 찾은 다음 정적 CreateFloatingDateRule 또는 CreateFixedDateRule 메서드를 사용하여 값을 만듭니다.

2

Hello_. 너무 늦었을 수도 있지만이 목적을 위해 사용한 코드는 여기에 게시 할 것입니다. 이것은 아마도 누군가 그것을 구현할 때 안전 할 수 있습니다. 나는 링크의 도움으로 실제로 그것을했습니다 @ Jamiegs 대답입니다.

public static DateTime? GetNextTransition(DateTime asOfTime, TimeZoneInfo timeZone) 
    { 
     TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules(); 
     if (adjustments.Length == 0) 
     { 
      // if no adjustment then no transition date exists 
      return null; 
     } 

     int year = asOfTime.Year; 
     TimeZoneInfo.AdjustmentRule adjustment = null; 
     foreach (TimeZoneInfo.AdjustmentRule adj in adjustments) 
     { 
      // Determine if this adjustment rule covers year desired 
      if (adj.DateStart.Year <= year && adj.DateEnd.Year >= year) 
      { 
       adjustment = adj; 
       break; 
      } 
     } 

     if (adjustment == null) 
     { 
      // no adjustment found so no transition date exists in the range 
      return null; 
     } 


     DateTime dtAdjustmentStart = GetAdjustmentDate(adjustment.DaylightTransitionStart, year); 
     DateTime dtAdjustmentEnd = GetAdjustmentDate(adjustment.DaylightTransitionEnd, year); 


     if (dtAdjustmentStart >= asOfTime) 
     { 
      // if adjusment start date is greater than asOfTime date then this should be the next transition date 
      return dtAdjustmentStart; 
     } 
     else if (dtAdjustmentEnd >= asOfTime) 
     { 
      // otherwise adjustment end date should be the next transition date 
      return dtAdjustmentEnd; 
     } 
     else 
     { 
      // then it should be the next year's DaylightTransitionStart 

      year++; 
      foreach (TimeZoneInfo.AdjustmentRule adj in adjustments) 
      { 
       // Determine if this adjustment rule covers year desired 
       if (adj.DateStart.Year <= year && adj.DateEnd.Year >= year) 
       { 
        adjustment = adj; 
        break; 
       } 
      } 

      dtAdjustmentStart = GetAdjustmentDate(adjustment.DaylightTransitionStart, year); 
      return dtAdjustmentStart; 
     } 
    } 


    public static DateTime GetAdjustmentDate(TimeZoneInfo.TransitionTime transitionTime, int year) 
    { 
     if (transitionTime.IsFixedDateRule) 
     { 
      return new DateTime(year, transitionTime.Month, transitionTime.Day); 
     } 
     else 
     { 
      // For non-fixed date rules, get local calendar 
      Calendar cal = CultureInfo.CurrentCulture.Calendar; 
      // Get first day of week for transition 
      // For example, the 3rd week starts no earlier than the 15th of the month 
      int startOfWeek = transitionTime.Week * 7 - 6; 
      // What day of the week does the month start on? 
      int firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transitionTime.Month, 1)); 
      // Determine how much start date has to be adjusted 
      int transitionDay; 
      int changeDayOfWeek = (int)transitionTime.DayOfWeek; 

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

      // Adjust for months with no fifth week 
      if (transitionDay > cal.GetDaysInMonth(year, transitionTime.Month)) 
       transitionDay -= 7; 

      return new DateTime(year, transitionTime.Month, transitionDay, transitionTime.TimeOfDay.Hour, transitionTime.TimeOfDay.Minute, transitionTime.TimeOfDay.Second); 
     } 
    } 

샘플 사용은 다음과 같이 표시됩니다

// This should give you DateTime object for date 26 March 2017 
// because this date is first transition date after 1 January 2017 for Central Europe Standard Time zone 
DateTime nextTransitionDate = GetNextTransition(new DateTime(2017, 1, 1), TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time")) 

당신은 내가 here 함께 연주 코드를 찾을 수 있습니다.

관련 문제