programing

날짜 범위를 순환하려면 어떻게 해야 합니까?

subpage 2023. 5. 9. 22:45
반응형

날짜 범위를 순환하려면 어떻게 해야 합니까?

루프/카운터 유형 솔루션에 끔찍한 것을 사용하지 않고 어떻게 해야 하는지조차 잘 모르겠습니다.문제는 다음과 같습니다.

시작 날짜와 종료 날짜의 두 가지 날짜가 주어지며, 지정된 간격으로 조치를 취해야 합니다.예를 들어, 2009년 3월 10일부터 2009년 3월 26일까지의 모든 날짜에 대해 목록에 항목을 만들어야 합니다.제 의견은 다음과 같습니다.

DateTime StartDate = "3/10/2009";
DateTime EndDate = "3/26/2009";
int DayInterval = 3;

제 출력물은 다음 날짜가 포함된 목록입니다.

3/13/2009 3/16/2009 3/19/2009 3/22/2009 3/25/2009

그럼 제가 어떻게 이런 일을 할 수 있을까요?저는 이렇게 별도의 카운터가 있는 범위에서 매일 반복되는 for 루프를 사용하는 것에 대해 생각했습니다.

int count = 0;

for(int i = 0; i < n; i++)
{
     count++;
     if(count >= DayInterval)
     {
          //take action
          count = 0;
     }

}

하지만 더 좋은 방법이 있을 것 같습니까?

글쎄, 당신은 어떻게든 그것들을 둘러볼 필요가 있을 것입니다.저는 다음과 같은 방법을 정의하는 것을 선호합니다.

public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
    for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
        yield return day;
}

그런 다음 다음과 같이 사용할 수 있습니다.

foreach (DateTime day in EachDay(StartDate, EndDate))
    // print it or whatever

이런 식으로 이틀에 한 번, 사흘에 한 번, 평일에만 칠 수 있습니다.예를 들어, "시작" 날짜로 시작하여 3일마다 돌아오려면, 그냥 전화하면 됩니다.AddDays(3)대신에 순환하여AddDays(1).

나는 있습니다RangeMiscUtil의 클래스는 유용하다고 생각할 수 있습니다.다양한 확장 방법과 결합하여 다음을 수행할 수 있습니다.

foreach (DateTime date in StartDate.To(EndDate).ExcludeEnd()
                                   .Step(DayInterval.Days())
{
    // Do something with the date
}

(끝을 제외할 수도 있고 안 할 수도 있습니다 - 저는 그저 예로 그것을 제공할 것이라고 생각했습니다.

이것은 기본적으로 mquander의 솔루션의 준비된(그리고 더 일반적인) 형태입니다.

예를 들어, 당신은 시도할 수 있습니다.

DateTime StartDate = new DateTime(2009, 3, 10);
DateTime EndDate = new DateTime(2009, 3, 26);
int DayInterval = 3;

List<DateTime> dateList = new List<DateTime>();
while (StartDate.AddDays(DayInterval) <= EndDate)
{
   StartDate = StartDate.AddDays(DayInterval);
   dateList.Add(StartDate);
}

확장에 사용된 @mquander 및 @Yogurt The Wise의 코드:

public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
    for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
        yield return day;
}

public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
    for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1))
        yield return month;
}

public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
    return EachDay(dateFrom, dateTo);
}

public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
    return EachMonth(dateFrom, dateTo);
}

1년 후, 그것이 누군가에게 도움이 되기를,

이 버전에는 유연성을 높이기 위해 술어가 포함되어 있습니다.

사용.

var today = DateTime.UtcNow;
var birthday = new DateTime(2018, 01, 01);

매일 내 생일까지

var toBirthday = today.RangeTo(birthday);  

내 생일에 매달, Step 2달

var toBirthday = today.RangeTo(birthday, x => x.AddMonths(2));

매년 나의 생일까지

var toBirthday = today.RangeTo(birthday, x => x.AddYears(1));

사용하다RangeFrom대신

// same result
var fromToday = birthday.RangeFrom(today);
var toBirthday = today.RangeTo(birthday);

실행

public static class DateTimeExtensions 
{

    public static IEnumerable<DateTime> RangeTo(this DateTime from, DateTime to, Func<DateTime, DateTime> step = null)
    {
        if (step == null)
        {
            step = x => x.AddDays(1);
        }

        while (from < to)
        {
            yield return from;
            from = step(from);
        }
    }

    public static IEnumerable<DateTime> RangeFrom(this DateTime to, DateTime from, Func<DateTime, DateTime> step = null)
    {
        return from.RangeTo(to, step);
    }
}

엑스트라

다음과 같은 경우 예외를 발생시킬 수 있습니다.fromDate > toDate대신 빈 범위를 반환하는 것이 좋습니다.[]

DateTime startDate = new DateTime(2009, 3, 10);
DateTime stopDate = new DateTime(2009, 3, 26);
int interval = 3;

for (DateTime dateTime=startDate;
     dateTime < stopDate; 
     dateTime += TimeSpan.FromDays(interval))
{

}
DateTime begindate = Convert.ToDateTime("01/Jan/2018");
DateTime enddate = Convert.ToDateTime("12 Feb 2018");
 while (begindate < enddate)
 {
    begindate= begindate.AddDays(1);
    Console.WriteLine(begindate + "  " + enddate);
 }

문제에 따르면 당신은 이것을 시도할 수 있습니다...

// looping between date range    
while (startDate <= endDate)
{
    //here will be your code block...

    startDate = startDate.AddDays(1);
}

감사합니다...

DateTime startDate = new DateTime(2009, 3, 10);
DateTime stopDate = new DateTime(2009, 3, 26);
int interval = 3;

while ((startDate = startDate.AddDays(interval)) <= stopDate)
{
    // do your thing
}

여기 2020년 제 2센트입니다.

Enumerable.Range(0, (endDate - startDate).Days + 1)
.ToList()
.Select(a => startDate.AddDays(a));

사용할 수 있습니다.DateTime.AddDays()추가할 기능DayInterval에게StartDate그리고 그것이 더 작은지 확인합니다.EndDate.

대신 반복기를 작성하는 것을 고려할 수 있으며, 이를 통해 '+'와 같은 일반적인 'for' 루프 구문을 사용할 수 있습니다.검색해보니 여기 StackOverflow에서 DateTime을 반복 가능하게 만드는 데 대한 포인터를 제공하는 비슷한 질문이 대답되어 있습니다.

당신은 루프에서 더 나은 해결책이 있을 때 날짜를 놓치지 않도록 여기서 주의해야 합니다.

이렇게 하면 시작 날짜의 첫 번째 날짜가 제공되고 증분하기 전에 루프에서 사용되며 마지막 종료 날짜를 포함한 모든 날짜가 <= 종료 날짜로 처리됩니다.

그래서 위의 답이 맞는 답입니다.

while (startdate <= enddate)
{
    // do something with the startdate
    startdate = startdate.adddays(interval);
}

이것을 사용할 수 있습니다.

 DateTime dt0 = new DateTime(2009, 3, 10);
 DateTime dt1 = new DateTime(2009, 3, 26);

 for (; dt0.Date <= dt1.Date; dt0=dt0.AddDays(3))
 {
    //Console.WriteLine(dt0.Date.ToString("yyyy-MM-dd"));
    //take action
 }

15분마다 반복합니다.

DateTime startDate = DateTime.Parse("2018-06-24 06:00");
        DateTime endDate = DateTime.Parse("2018-06-24 11:45");

        while (startDate.AddMinutes(15) <= endDate)
        {

            Console.WriteLine(startDate.ToString("yyyy-MM-dd HH:mm"));
            startDate = startDate.AddMinutes(15);
        }

@jacob-sobus, @mquander, @Yogurt 정확하지 않습니다.다음 날 필요하면 00:00 시간을 대부분 기다립니다.

    public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
    {
        for (var day = from.Date; day.Date <= thru.Date; day = day.NextDay())
            yield return day;
    }

    public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
    {
        for (var month = from.Date; month.Date <= thru.Date || month.Year == thru.Year && month.Month == thru.Month; month = month.NextMonth())
            yield return month;
    }

    public static IEnumerable<DateTime> EachYear(DateTime from, DateTime thru)
    {
        for (var year = from.Date; year.Date <= thru.Date || year.Year == thru.Year; year = year.NextYear())
            yield return year;
    }

    public static DateTime NextDay(this DateTime date)
    {
        return date.AddTicks(TimeSpan.TicksPerDay - date.TimeOfDay.Ticks);
    }

    public static DateTime NextMonth(this DateTime date)
    {
        return date.AddTicks(TimeSpan.TicksPerDay * DateTime.DaysInMonth(date.Year, date.Month) - (date.TimeOfDay.Ticks + TimeSpan.TicksPerDay * (date.Day - 1)));
    }

    public static DateTime NextYear(this DateTime date)
    {
        var yearTicks = (new DateTime(date.Year + 1, 1, 1) - new DateTime(date.Year, 1, 1)).Ticks;
        var ticks = (date - new DateTime(date.Year, 1, 1)).Ticks;
        return date.AddTicks(yearTicks - ticks);
    }

    public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
    {
        return EachDay(dateFrom, dateTo);
    }

    public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
    {
        return EachMonth(dateFrom, dateTo);
    }

    public static IEnumerable<DateTime> EachYearTo(this DateTime dateFrom, DateTime dateTo)
    {
        return EachYear(dateFrom, dateTo);
    }

의 날짜를 OODate로 한다면, 나 OADate와 할 수 .double번호.

DateTime startDate = new DateTime(2022, 1, 1);
DateTime endDate = new DateTime(2022, 12, 31);

for (double loopDate = startDate.ToOADate(); loopDate <= endDate.ToOADate(); loopDate++)
{
    DateTime selectedDate;
    selectedDate = DateTime.FromOADate(loopDate);
}

언급URL : https://stackoverflow.com/questions/1847580/how-do-i-loop-through-a-date-range

반응형