gpt4 book ai didi

c# - 如何减去两个日期导致几天或几周?

转载 作者:行者123 更新时间:2023-11-30 19:26:27 25 4
gpt4 key购买 nike

我正在寻找可以输入 2 个日期的函数:

这样开始:

         public static String getDaysOrWeeksFromDateDiff(DateTime first, DateTime second)
{
//this function will substract the date from the other and result days if < 8 and weeks if > 7

return "1 week";
}

我在下面尝试过这个函数,但它给了我一个负数的日期(我在计算中不知何故错过了年份)

 public static String getDaysOrWeeksFromDateDiff(DateTime first, DateTime second)
{
var cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
var weeknr = cal.GetWeekOfYear(first, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
var weeknr2 = cal.GetWeekOfYear(second, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
String strReturnValue;
if (weeknr == weeknr2)
{
var dagen = first.Day - second.Day;
strReturnValue = (dagen == 0 ? "today" : (dagen == 1 ? "1 day" : dagen + " days"));
}
else
{
strReturnValue = (weeknr - weeknr2 == 1 ? "1 week" : weeknr - weeknr2 + " weeks");
}
return strReturnValue;
}

最佳答案

您可以 subtract dates directly :

TimeSpan difference = second - first;

这将返回一个 TimeSpan object ,您可以轻松查询,例如

if (difference.Days >= 8) ...

Days 的数量转换为周应该是一个微不足道的练习,因为每周正好有 7 天...

(请注意,Days 将为您提供整数天数,而 TotalDays 将包括小数天数。)

关于c# - 如何减去两个日期导致几天或几周?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22832436/

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