program story

C #에서 두 'DateTime'사이의 모든 DateTime 가져 오기

inputbox 2020. 10. 28. 08:03
반응형

C #에서 두 'DateTime'사이의 모든 DateTime 가져 오기


나는 두 개의를 가지고 있으며이 날짜 사이에 모든를 DateTime얻고 싶습니다 DateTime. 예를 들어 내 날짜가 01.01.2010-05.01.2010과 같은 경우 내 함수는 날짜 목록 (목록)을 반환해야하며 01.01.2010, 02.01.2010, 03.01.2010, 04.01.2010 및 05.01.2010.

나는 이와 같은 함수를 썼다. 내 날짜가 한 달이면 잘 작동합니다. 내 날짜가 2010 년 1 월 1 일-2010 년 5 월 2 일 같은 경우 작동하지 않습니다. 월이 바뀌고 내 기능이 처리 할 수 ​​없기 때문입니다. 두 날짜 사이의 모든 날짜를 반환하는 C # 함수가 있습니까? 또는 월 변경을 어떻게 처리 할 수 ​​있습니까?

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));
        }

질문이 해결되었습니다. 사용에 대한 Tim Robinson의 간단한 답변을 참조하십시오.


DateTime.NET Core 대신 루프에서 직접 개체 를 사용할 수 있습니다 int. DateTime.AddDays월 종료를 올바르게 처리합니다.

for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
    allDates.Add(date);

이런 건 어때?

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

편집 : 지금 테스트되었습니다. :)


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);
    }
}

당신은 너무 가까웠어요. 그냥 하루를 사용하지 말고 전체 날짜를 사용하세요

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();
}

다음은 방법을 보여주는 빠른 콘솔 앱입니다 AddDays(). 대신 사용하세요.

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;
    }
}

문자열의 더 낮은 날짜 값과 더 높은 날짜 값 및 세 번째 매개 변수로 빈도가 주어지면이 메소드는 날짜 사전을 리턴해야합니다. 여기서 키는 날짜 범위의 시작 값이고 값은 해당 범위입니다. 빈도가 매주 또는 매월이면 제대로 작동합니다. 필요에 따라 맞춤 설정할 수 있습니다. 전달 된 날짜 값은 적절한 형식이어야합니다. 그렇지 않으면 tryParseExact 등을 사용하여 형식을 지정해야 할 수도 있습니다.

    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;
    }

날짜에 다른 시간이 포함되면 상위 솔루션이 실패합니다. 다음은 하루 종일 사용할 수있는 솔루션입니다.

하루 종일 :

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;
    }

모든 시간 :

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;
    }

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();
}

참고URL : https://stackoverflow.com/questions/3227927/getting-all-datetimes-between-two-datetimes-in-c-sharp

반응형