在C#中获取两个日期之间的星期范围

时间:2018-08-01 08:42:18

标签: c# asp.net datetime

我有一个表单,用户可以在其中输入起始日期和结束日期,并且在提交表单时,我将生成一个Excel文件,其中包含指定的起始日期和周数范围。

例如,如果用户输入:DllNotFoundException: FirebaseCppApp-5.2.0 at (wrapper managed-to-native) Firebase.AppUtilPINVOKE/SWIGExceptionHelper:SWIGRegisterExceptionCallbacks_AppUtil (Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate,Firebase.AppUtilPINVOKE/SWIGExceptionHelper/ExceptionDelegate) at Firebase.AppUtilPINVOKE+SWIGExceptionHelper..cctor () [0x00000] in <filename unknown>:0 Rethrow as TypeInitializationException: An exception was thrown by the type initialize excel文件将包含以下列:

-1/8/2018 - 15/8/2018

-1/8/2018 to 7/8/2018

-8/8/2018 to 14/8/2018

如何实现按日期划分日期范围

感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

我的想法是:您累积一个chunkDay到开始日期(在您的情况下,从1到7是6天)直到日期结束。小提琴起作用:https://dotnetfiddle.net/rrN8Yd

它将返回上周作为您的要求15/8/2018 to 21/8/2018

    public static IEnumerable<Tuple<DateTime, DateTime>> Split(DateTime start, DateTime end, int chunk)
    {
        DateTime chunkEnd;
        while ((chunkEnd = start.AddDays(chunk)) < end)
        {
            yield return Tuple.Create(start, chunkEnd);
            start = chunkEnd.AddDays(1);
        }
        yield return Tuple.Create(start, start.AddDays(chunk));
    }

使用此输入

    foreach( var t in Split(new DateTime(2018,8,1), new DateTime(2018,8,17),6)){
            Console.WriteLine(t.Item1.ToString() + " " + t.Item2.ToString());
        }

我有输出

8/1/2018 12:00:00 AM 8/7/2018 12:00:00 AM
8/8/2018 12:00:00 AM 8/14/2018 12:00:00 AM
8/15/2018 12:00:00 AM 8/21/2018 12:00:00 AM

答案 1 :(得分:0)

using System.IO;
using System;

class Program
{
    static void Main()
    {
        DateTime fromDate = new DateTime(2018,8,1);
        DateTime toDate = new DateTime(2018,8,15);
        Console.WriteLine("From: "+fromDate.ToString("dd/MM/yyyy"));
        Console.WriteLine("To  : "+toDate.ToString("dd/MM/yyyy"));

        DateTime startDate = fromDate;

        do
        {
            Console.WriteLine(startDate.ToString("dd/MM/yyyy")+"-"+startDate.AddDays(6).ToString("dd/MM/yyyy"));
            startDate = startDate.AddDays(7);
        }
        while(startDate < toDate.AddDays(1));
    }
}

Try it online

({do{}while()while(){}相同)