2016-10-20 53 views
1

我遇到了一個場景,我需要將Interval的值轉換爲NodaTime中的LocalDate的Enumerable集合。我怎樣才能做到這一點?如何將時間間隔轉換爲NodaTime中的LocalDate範圍?

下面是代碼

Interval invl = obj.Interval; 
//Here is the Interval value i.e.,{2016-10-20T00:00:00Z/2016-11-03T00:00:00Z} 

我怎樣才能形成這些間隔之間的日期範圍是多少?

在此先感謝。

回答

3

稍微替代方法的一個由Niyoko給出:

  • 轉換既Instant值到LocalDate
  • 實現一個範圍之間EEN他們

我假設的間隔是獨一無二 - 因此,如果終點代表正是午夜目標時區,你排除的那一天,否則你包括它。

因此,下面的方法包括在給定時區內的時間間隔內覆蓋的每個日期。

public IEnumerable<LocalDate> DatesInInterval(Interval interval, DateTimeZone zone) 
{ 
    LocalDate start = interval.Start.InZone(zone).Date; 
    ZonedDateTime endZonedDateTime = interval.End.InZone(zone); 
    LocalDate end = endLocalDateTime.Date; 
    if (endLocalDateTime.TimeOfDay == LocalTime.Midnight) 
    { 
     end = end.PlusDays(-1); 
    } 
    for (LocalDate date = start; date <= end; date = date.PlusDays(1)) 
    { 
     yield return date; 
    } 
} 
+0

謝謝。我會試試你的解決方案。此外,我收到一個錯誤,如'不能隱式轉換類型'NodaTime.ZonedDateTime'到'NodaTime.LocalDateTime'。將LocalDateTime轉換爲ZonedDateTime解決了錯誤。我做對了嗎? – Karthik

+0

@Karthik:是的 - 現在修好了樣品,謝謝。 –

+0

謝謝@Jon Skeet。 – Karthik

2

使用此代碼:

var l = Enumerable.Range(0, int.MaxValue) 
      .Select(x => Period.FromDays(x)) 
      .Select(x => LocalDate.Add(interval.Start.InZone(localZone).Date, x)) 
      .TakeWhile(x => x.CompareTo(interval.End.InZone(localZone).Date) <= 0); 

實施例:

var localZone = DateTimeZone.ForOffset(Offset.FromHours(7)); 

var start = Instant.FromDateTimeOffset(new DateTimeOffset(new DateTime(2016, 10, 1))); 
var end = Instant.FromDateTimeOffset(new DateTimeOffset(new DateTime(2016, 10, 25))); 

var interval = new Interval(start, end); 

var l = Enumerable.Range(0, int.MaxValue) 
     .Select(x => Period.FromDays(x)) 
     .Select(x => LocalDate.Add(interval.Start.InZone(localZone).Date, x)) 
     .TakeWhile(x => x.CompareTo(interval.End.InZone(localZone).Date) <= 0); 

foreach (var localDate in l) 
{ 
    Console.WriteLine(localDate); 
} 
+0

謝謝。你的解決方案工作正常但是你能解釋一下DateTimeZone對象'localZone'嗎?因爲它設置了偏移值。 – Karthik

+0

@Karthik它用於將'Instant'轉換爲'LocalDate',因爲'Instant'是與時區無關的。根據當地時區更改它。 –

+0

或者你可以通過調用'DateTimeZoneProviders.Bcl.GetSystemDefault()' –

相關問題