【问题标题】:add particular days from given date for one year从给定日期添加特定日期为一年
【发布时间】:2015-12-15 12:59:17
【问题描述】:

我的开始日期类似于“2015-03-10”。我想从这个开始日期起每月增加 1.25 天。例如,我的开始日期为“2015-03-10”,那么今年的天数将为 12.50。 (从 3 月开始,每个月 1.25 天)。

给定日期:2015-11-10 需要添加天数到 2016 年 3 月 31 日:1.25 * 5(从 11 月开始,这里是 5)(每个月添加 1.25 天)今年的天数:6.25 (年从四月算起,年末算三月。)

我如何在 c# 中做到这一点,任何人都可以帮助我做到这一点 提前致谢

【问题讨论】:

  • SQL标签怎么来的?
  • @jarlh 抱歉,它不在那里,谢谢
  • 很不清楚您在这里要求什么 - 似乎有两种不同的情况 - 一种是年底是 12 月,另一种是 3 月。请尝试拼凑一个minimal reproducible example。另请注意,从 2015-03-10 到 2016 年 3 月是 12 个月,而不是 10...
  • 你试过实现它吗? .NET Framework 具有出色的 DateTime 结构。

标签: c# date datetime


【解决方案1】:

根据您的帖子,此示例忽略月份中的日期:

DateTime start;
DateTime end;

// assuming end > start
double value = 1.25 * (end.Month - start.Month + 12 * (end.Year - start.Year) + 1);

编辑:我可以通过一些步骤帮助您理解这行代码拆分:

DateTime start = DateTime.Now;
DateTime end = new DateTime(start.Year, 3, 31);

if (start.Month > 3) 
    end = end.AddYear(1);

double years = end.Year - start.Year;
double months = end.Month - start.Month + 1;
months += (years * 12);
double value = 1.25 * months;

【讨论】:

  • 感谢您的回复。我将开始日期作为当前日期。我如何才能将结束日期作为财政年度(明年 3 月 31 日)
  • 对不起,我不确定你的问题。您想以某种方式自动计算结束日期吗?总是下一个 3 月 31 日吗?如果是则 "if (start.Month
  • 我通过以下方式获得明年 3 月 31 日的最后一个日期: DateTime endDate = new DateTime(DateTime.Today.Year + 1, 4, 1).AddDays(-1);现在想要获得 1.25 *(月份之间的差异)。这里月份之间的差异应为 5(即 11 月应作为财政年度的第 8 个月)...
  • 为什么是 "new DateTime(DateTime.Today.Year + 1, 4, 1).AddDays(-1)" 而不是 "new DateTime(DateTime.Today.Year + 1, 3, 31) ”。无论如何,这不适用于 1 月和 2 月(请参阅我之前的评论)。
【解决方案2】:

我通过以下方式得到它:

DateTime endDate = new DateTime(DateTime.Today.Year + 1, 4, 1).AddDays(-1);
if (Convert.ToDateTime(empHiredDate).Month > 4)
{
    finMonth = Convert.ToDateTime(empHiredDate).Month - 4;
    finMonth = 12 - finMonth;
    avail =Convert.ToString(finMonth * 1.25);
}
else if (Convert.ToDateTime(empHiredDate).Month < 3)
{
    finMonth = Convert.ToDateTime(empHiredDate).Month + 8;
    finMonth = 12 - finMonth;
    avail = Convert.ToString(finMonth * 1.25);
}
else if (Convert.ToDateTime(empHiredDate).Month == 4)
{
    avail = Convert.ToString(12 * 1.25);
}
else if (Convert.ToDateTime(empHiredDate).Month == 3)
{
    avail = Convert.ToString(1 * 1.25);
}

【讨论】:

  • 这不是你问的。对于今天的日期(2015 年 12 月 16 日),您将输出 9*1.25=11.25。您的问题不清楚,您的解决方案也不清楚。
  • 现在它似乎工作了,但它是不必要的复杂。您已经编写了大约 10 行代码,并且得到了与我的答案相同的结果(1 行代码)。我的感觉是,您正在尝试遵循一些合乎逻辑的步骤来获得结果,但是您必须学习如何将“复杂”问题简化为简单的操作。
  • 我已经编辑了我的答案以帮助您理解它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多