gpt4 book ai didi

c# - 生成每周日期

转载 作者:行者123 更新时间:2023-11-30 20:06:42 25 4
gpt4 key购买 nike

我确信这已经完成了,所以我正在寻找一个有效的解决方案而不是自己的自定义解决方案。

给定 2 个日期,我试图生成准确的每周日期(用于创建每周订单)。

编辑:我需要使用 .NET 标准库来执行此操作。

Example below,

Given 28/02/2012 and 6/03/2012.

so, the weekly dates generated are
- Week From(Start Monday): Week To(End Sunday):
- 27/02/2012 - 04/03/2012
- 05/03/2012 - 11/03/2012

Another example (1 month)

Given 01/02/2012 and 29/02/2012
so, the weekly dates generated are
- Week From(Start Monday): Week To(End Sunday):
- 30/01/2012 - 05/02/2012
- 06/02/2012 - 12/02/2012
- 13/02/2012 - 19/02/2012
- 20/02/2012 - 26/02/2012
- 27/02/2012 - 04/03/2012

我在 C# 中执行此操作。这是以前做过的吗?介意分享解决方案吗?

干杯

最佳答案

这是一个使用 Noda Time 的解决方案.诚然,它需要 <=我现在正在实现的运算符 - 但这不会花很长时间:)

using System;
using NodaTime;

class Test
{
static void Main()
{
ShowDates(new LocalDate(2012, 2, 28), new LocalDate(2012, 3, 6));
ShowDates(new LocalDate(2012, 2, 1), new LocalDate(2012, 2, 29));
}

static void ShowDates(LocalDate start, LocalDate end)
{
// Previous is always strict - increment start so that
// it *can* be the first day, then find the previous
// Monday
var current = start.PlusDays(1).Previous(IsoDayOfWeek.Monday);
while (current <= end)
{
Console.WriteLine("{0} - {1}", current,
current.Next(IsoDayOfWeek.Sunday));
current = current.PlusWeeks(1);
}
}
}

显然可以在正常情况下执行此操作 DateTime同样,但没有真正表示“只是一个日期”,这使得代码不太清晰 - 你需要实现 Previous自己。

编辑:例如,在这种情况下您可以使用:

using System;

class Test
{
static void Main()
{
ShowDates(new DateTime(2012, 2, 28), new DateTime(2012, 3, 6));
ShowDates(new DateTime(2012, 2, 1), new DateTime(2012, 2, 29));
}

static void ShowDates(DateTime start, DateTime end)
{
// In DateTime, 0=Sunday
var daysToSubtract = ((int) start.DayOfWeek + 6) % 7;
var current = start.AddDays(-daysToSubtract);

while (current <= end)
{
Console.WriteLine("{0} - {1}", current, current.AddDays(6));
current = current.AddDays(7);
}
}
}

关于c# - 生成每周日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9451605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com