【问题标题】:DateTime manipulation日期时间操作
【发布时间】:2012-05-14 10:21:10
【问题描述】:

这是我的代码:

DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);
DateTime endDate = Convert.ToDateTime( orderDate );

orderDate 是我输入的有效日期。

我如何始终保证 orderDate 的 startDate 是上个月的第一天? 我如何始终保证 endDate 是 orderDate 每月的最后一天?

例子:

orderDate = 5/4/2012

I want startDate to be 4/1/2012 (or 04/1/2012 whichever is default)
I want endDate to be 4/30/2012

我怎样才能做到这一点?

【问题讨论】:

  • 为什么要将 DateTime 转换为 DateTime?
  • @TimeSchmelter 因为 orderDate 是从两个参数传入的字符串,可以通过文本框或查询字符串进行更改。
  • @JamesWilson:我刚刚问过,因为你说过 “orderDate 是我传入的有效日期”,而且确实有 an overload 需要一个 DateTime。
  • 没有 4/31/2012 :)

标签: c# datetime


【解决方案1】:
var orderDate = DateTime.Now.Date;
var endDate = orderDate.AddDays(-orderDate.Day);
var startDate  = endDate.AddDays(-(endDate.Day - 1));

【讨论】:

    【解决方案2】:
    DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);
    // set to first of month
    startDate = startDate.AddDays(1-startDate.Day);
    
    // Set end date to last of month, which is one day before first of next month
    DateTime endDate = startDate.AddMonths(1).AddDays(-1);
    

    【讨论】:

    • 我将采用这种方法。这有可能像这个线程中的另一个答案一样在 12 月或 1 月中断吗?只是想覆盖我所有的基地。
    • @James Wilson - 与您执行的任何代码一样,因此无法保证 :) 除非它已融入您的 ASP.NET 项目,否则您应该为它编写单元测试。无论如何,您绝对应该尽可能多地测试边缘案例(日期为 2000 年 1 月、12 月等)
    【解决方案3】:

    使用 DateTime 构造函数,该构造函数为每一年、每月、每一天……获取单独的值,并相应地调整它们(即,每月的第一天表示天 = 1)。

    【讨论】:

      【解决方案4】:
      DateTime startDate = new DateTime( orderDate.Month == 1 ? orderDate.Year - 1 : orderDate.Year, orderDate.Month - 1, 1);
      DateTime endDate = new DateTime(orderDate.Year, orderDate.Month, DateTime.DaysInMonth(orderDate.Year, OrderDate.Month));
      

      【讨论】:

      • -1 如果你的约会是在一月份呢?你将有错误的一年。如果答案得到纠正,我将删除反对票。
      • 我删除了我的反对票,但我认为这里不需要条件运算符。
      • 不,我的意思是有几种方法可以做到这一点。我试图把它塞进一行哈哈
      【解决方案5】:
      origDate = startDate.AddMonths(-1);
      DateTime myDate = new DateTime(origDate.Year, origDate.Month, 1);
      

      http://msdn.microsoft.com/en-us/library/xcfzdy4x.aspx

      类似这样的事情......我们经常这样做,以至于我们刚刚在 date 上创建了一个扩展方法。

      【讨论】:

        猜你喜欢
        • 2013-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        • 2014-09-08
        • 2012-11-23
        • 2015-10-02
        相关资源
        最近更新 更多