2010-12-10 9 views
5

Powiedzmy masz datę ciąg jak następuje:daty w stenografii

11/15/2010, 12/1/10, 12/2/10, 12/3/10, 12/4/10, 12/9/10 

Jak można skrócić ten ciąg jak poniżej (lub coś podobnego)

11/15/2010, 12/1-4, 9/10 

Bo wyobrazić 30 dni z rzędu lepiej byłoby zobaczyć 12/1-31/10 niż wszystkie daty na liście.

Tylko po to, aby był bardziej kompaktowy?

Dzięki, pręt .

+0

Zakładam patrzymy na daty w formacie US angielskiego? –

+0

w prawo, lub jeśli istnieje sposób dla dowolnego formatu, który jest mile widziany. – Rod

+0

Nie widzę wzoru skracania. Skąd pochodzi 11/1/2010? A 9/10 to miesiąc i rok ostatniej daty na wejściu, podczas gdy poprzedni wpis na wyjściu to miesiąc i zakres dni. – Amy

Odpowiedz

3
public class so_4413380 
{ 
    private class DateGroup 
    { 
     public IList<DateTime> Dates { get; set; } 

     public DateTime First 
     { 
      get { return Dates.OrderBy(d => d).FirstOrDefault(); } 
     } 

     public DateTime Last 
     { 
      get { return Dates.OrderBy(d => d).LastOrDefault(); } 
     } 

     public DateGroup() 
     { 
      Dates = new List<DateTime>(); 
     } 
    } 

    public void Execute() 
    { 
     var dateTimeFormat = CultureInfo.GetCultureInfo("en-US").DateTimeFormat; 
     var dates = new[] { "11/15/2010", "12/1/10", "12/2/10", "12/3/10", "12/4/10", "12/9/10" }; 
     var realDates = dates.Select(s => DateTime.Parse(s, dateTimeFormat)); 
     var dateGroups = new List<DateGroup>(); 

     DateTime lastDate = DateTime.MinValue; 
     foreach (var date in realDates.OrderBy(d => d)) 
     { 
      if (date.Month == lastDate.Month && (date - lastDate).Days <= 1) 
      { 
       var dateGroup = dateGroups.LastOrDefault(); 
       dateGroup.Dates.Add(date); 
      } 
      else 
      { 
       var dateGroup = new DateGroup(); 
       dateGroups.Add(dateGroup); 

       dateGroup.Dates.Add(date); 
      } 

      lastDate = date; 
     } 

     foreach (var dateGroup in dateGroups) 
     { 
      if (dateGroup.Dates.Count == 1) 
      { 
       Console.WriteLine(dateGroup.First.ToString(dateTimeFormat.ShortDatePattern, dateTimeFormat)); 
      } 
      else 
      { 
       int firstDay = dateGroup.First.Day; 
       int lastDay = dateGroup.Last.Day; 

       var dateString = dateTimeFormat.ShortDatePattern.Replace("d", firstDay + "-" + lastDay); 

       Console.WriteLine(dateGroup.First.ToString(dateString, dateTimeFormat)); 
      } 
     } 

     Console.ReadLine(); 
    } 
} 

Produkuje

11/15/2010 
12/1-4/2010 
12/9/2010 
+0

+1 Za włączenie kultury –

+0

Dziękuję bardzo za pomoc i świeżą perspektywę. – Rod