【问题标题】:Determine current year or previous year based upon month selection根据月份选择确定当前年份或上一年
【发布时间】:2011-09-23 20:26:15
【问题描述】:

我继承了一个用 C# 编写的存档程序。之前的开发人员只对归档上个月的数据感兴趣。但是,错过了一些月份,我的任务是添加功能以查看错过了哪些其他月份。

我坚持的部分是: 在确定错过的月份时,我需要确定该月份是今年的一部分还是上一年的一部分。

当前月份是关键。 如果当前月份是 9 月,则从 1 月到 9 月的月份被视为当年。

如果当前月份是 9 月,则 10 月到 12 月被视为上一年。 当然,随着每个月的进展,这将是一个滑动范围。

寻求指导。

【问题讨论】:

  • 您似乎已经回答了自己的问题。
  • 如果我有,我很难编码

标签: c# date


【解决方案1】:

除非我遗漏了什么,否则您只需将您遗漏的月份日期与DateTime.Today.Month进行比较

DateTime archiveDate;
if(someMonth > DateTime.Today.Month)
    archiveDate = new DateTime(DateTime.Today.Year - 1, someMonth, 1);
else
    archiveDate = new DateTime(DateTime.Today.Year, someMonth, 1);

【讨论】:

    【解决方案2】:

    使用 DateTime.Now.Month 它会为您提供实际的月份,您可以将其与您描述的其他日期进行比较,如果它小于或等于则它是当前年份,如果它大于上一年。

    然后您可以使用 DateTime.Now.AddYears(-1) 设置上一年存档的存档日期

    【讨论】:

      【解决方案3】:

      您可以获取当前月份数(通过DateTime.Month)并从比较月份中减去它并检查它是否大于零。

      示例:

      int month1 = 5;  //may
      int month2 = 4;  //apr
      bool isCurrentYear = (month1 - month2 >= 0);  //current year
      
      int month1 = 8;  //aug
      int month2 = 11;  //nov
      bool isCurrentYear = (month1 - month2 >= 0); //last year
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-24
        • 2018-03-02
        • 1970-01-01
        • 2015-09-28
        • 2014-01-06
        相关资源
        最近更新 更多