2010-07-12 46 views
60

Tôi có hai DateTime s và tôi muốn nhận tất cả DateTime giây trong các ngày này. Chẳng hạn như, nếu ngày của tôi giống như 01.01.2010 - 05.01.2010, hàm của tôi sẽ trả về cho tôi danh sách ngày tháng (Danh sách) và nó phải chứa 01.01.2010, 02.01.2010, 03.01.2010, 04.01.2010 và 05.01.2010.Bắt tất cả Ngày giờ giữa hai 'Ngày giờ trong C#

Tôi đã viết một chức năng như thế này. Nó hoạt động tốt, nếu ngày của tôi là trong một tháng. Nó sẽ không hoạt động nếu ngày của tôi giống như 01.01.2010 - 05.02.2010. Vì tháng đã thay đổi và chức năng của tôi không thể xử lý được. Có một hàm trong C# trả về tất cả các ngày giữa hai ngày không? Hoặc làm thế nào tôi có thể xử lý thay đổi tháng?

public void GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate) 
    { 
     List<DateTime> allDates = new List<DateTime>(); 

     int starting = startingDate.Day; 
     int ending = endingDate.Day; 

     for (int i = starting; i <= ending; i++) 
     { 
      allDates.Add(new DateTime(startingDate.Year, startingDate.Month, i)); 
     } 

Câu hỏi được giải quyết, xem câu trả lời đơn giản của Tim Robinson để sử dụng.

Trả lời

115

Bạn có thể sử dụng DateTime đối tượng trực tiếp trong vòng lặp, thay cho số int của mình. DateTime.AddDays xử lý tháng kết thúc chính xác.

for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1)) 
    allDates.Add(date); 
7
public IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate) 
{ 
    if (endingDate < startingDate) 
    { 
     throw new ArgumentException("endingDate should be after startingDate"); 
    } 
    var ts = endingDate - startingDate; 
    for (int i = 0; i < ts.TotalDays; i++) 
    { 
     yield return startingDate.AddDays(i); 
    } 
} 
+0

Nice sử dụng có năng suất, shoulda suy nghĩ về điều đó. – Jamiec

3

Bạn đã rất gần ... chỉ cần không sử dụng ban ngày, sử dụng toàn bộ ngày.

static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate) 
{ 
    List<DateTime> allDates = new List<DateTime>(); 


    for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1)) 
    { 
     allDates.Add(i); 
    } 
    return allDates.AsReadOnly(); 
} 
+1

+1 cho '.AsReadOnly();'. – Odys

52

Làm thế nào về điều này?

public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate) 
{ 
    return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1) 
        .Select(d => fromDate.AddDays(d)); 
} 

Chỉnh sửa: Đã kiểm tra ngay bây giờ. :)

+0

Chỉ là những gì tôi cần. Làm việc và thực sự sạch sẽ. – gligoran

1

Đây là một giao diện điều khiển ứng dụng nhanh chóng để chứng minh làm thế nào để làm điều đó - sử dụng AddDays() thay vì:

class Program 
{ 
    static void Main(string[] args) 
    { 

     GetDates(new DateTime(2010, 1, 1), new DateTime(2010, 2, 5)); 

     Console.ReadKey(); 
    } 

    static List<DateTime> GetDates(DateTime startDate, DateTime endDate) 
    { 
     List<DateTime> dates = new List<DateTime>(); 

     while ((startDate = startDate.AddDays(1)) < endDate) 
     { 
      dates.Add(startDate); 
     } 

     return dates; 
    } 
} 
+0

Chết tiệt, rất nhiều câu trả lời cho câu hỏi này. – slugster

1

Cho một giá trị lowerdate và giá trị ngày cao hơn trong chuỗi và một tần số như tham số thứ ba phương pháp này nên trả lại một từ điển của các ngày; trong đó khóa là giá trị bắt đầu của phạm vi ngày và giá trị là phạm vi tương ứng. Điều này làm việc tốt nếu tần suất là hàng tuần hoặc hàng tháng, bạn có thể tùy chỉnh nó theo nhu cầu của bạn. Giá trị ngày được chuyển phải ở định dạng phù hợp hoặc bạn có thể cần định dạng nó bằng tryParseExact hoặc một cái gì đó tương tự.

protected static Dictionary<DateTime, String> getDateRange(String lowerDate, String higherDate, String frequency) 
    { 
     DateTime startDate, endDate; 
     startDate = Convert.ToDateTime(lowerDate); 
     endDate = Convert.ToDateTime(higherDate); 

     Dictionary<DateTime, String> returnDict = new Dictionary<DateTime, String>(); 

     while (frequency.Equals("weekly") ? (startDate.AddDays(7) <= endDate) : (startDate.AddMonths(1) <= endDate)) 
     { 
      if (frequency.Equals("weekly")) 
      { 
       returnDict.Add(startDate, startDate + "-" + startDate.AddDays(7)); 
       startDate = startDate.AddDays(8); 
      } 
      if (frequency.Equals("monthly")) 
      { 
       returnDict.Add(startDate, startDate + "-" + startDate.AddMonths(1)); 
       startDate = startDate.AddMonths(1).AddDays(1); 
      } 
     } 

     returnDict.Add(startDate, startDate + "-" + endDate); 

     return returnDict; 
    } 
+0

Vui lòng định dạng mã để dòng đầu tiên của hàm cũng được định dạng là mã. Câu trả lời này không giải quyết được câu hỏi, vì anh ta viết rằng anh ta đã có hai DateTimes và muốn một List, nhưng hàm của bạn lấy các chuỗi thay vì DateTimes và trả về một từ điển thay vì một danh sách. Ngoài ra, anh ấy muốn mọi ngày giữa ngày bắt đầu và ngày kết thúc, không chỉ một lần một tuần hoặc mỗi tháng một lần. – tomsv

1

Giải pháp hàng đầu sẽ thất bại nếu ngày bao gồm các giờ khác nhau. Dưới đây là một giải pháp nhận được tất cả và giờ tất cả các ngày:

Tất Cả Các Ngày:

static public List<string> get_days_between_two_dates(DateTime start_date, DateTime end_date) 
    { 
     List<string> days_list = new List<string>(); 
     DateTime temp_start; 
     DateTime temp_end; 

     //--Normalize dates by getting rid of minues since they will get in the way when doing the loop 
     temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day); 
     temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day); 

     //--Example Should return 
     //--1-12-2014 5:59AM - 1-13-2014 6:01AM return 12 and 13 
     for (DateTime date = temp_start; date <= temp_end; date = date.AddDays(1)) 
     { 
      days_list.Add(date.ToShortDateString()); 
     } 

     return days_list; 
    } 

Tất cả các giờ:

static public List<string> get_hours_between_two_dates(DateTime start_date, DateTime end_date) 
    { 
     List<string> hours_24_list = new List<string>(); 
     DateTime temp_start; 
     DateTime temp_end; 

     //--Normalize dates by getting rid of minutes since they will get in the way when doing the loop 
     temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day, start_date.Hour, 0, 0); 
     temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day, end_date.Hour, 0, 0); 

     //--Example Should return 
     //--5:59AM - 6:01AM return 5am and 6am 
     for (DateTime date = temp_start; date <= temp_end; date = date.AddHours(1)) 
     { 
      hours_24_list.Add(date.ToShortTimeString()); 
     } 

     return hours_24_list; 
    } 
0
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate) 
{ 
    List<DateTime> allDates = new List<DateTime>(); 


    for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1)) 
    { 
     allDates.Add(i); 
    } 
    return allDates.AsReadOnly(); 
} 
Các vấn đề liên quan