确定具体的日期

本文关键字:日期 | 更新日期: 2023-09-27 18:18:31

我正在使用c#中的日期,需要计算一些进一步的日期。取当前的datetime

如何得到以下值?

  • 一天结束
  • 月末
  • 年度末

确定具体的日期

如果您所说的end of ...是指当天的12:59:59.999PM,那么:

  • 一天结束

    var today = DateTime.Today;
    var endOfDay = new DateTime(
        today.Year, 
        today.Month,
        today.Day,
        23,
        59,
        59,
        999
    );
    
  • 月末

    var today = DateTime.Today;
    var endOfMonth = new DateTime(
        today.Year, 
        today.Month,
        DateTime.DaysInMonth(today.Year, today.Month),
        23,
        59,
        59,
        999
    );
    
  • 年末

    var today = DateTime.Today;
    var endOfYear = new DateTime(
        today.Year,
        12,
        31,
        23,
        59,
        59,
        999
    );
    

如果你有别的意思,那就解释一下你的意思。

对于月底

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));

参见如何在c#中获得一个月的最后一天?

对于年末

DateTime endOfYear = new DateTime(today.Year, 12, 31);

对于一天的结束,假设一天的结束是在下午5点结束营业

DateTime endOfDay = new DateTime(today.Year, today.Month, today.day, 17, 0, 0); // Assuming the business end of day is at 5 PM

查看更多关于datetime的信息,请访问http://msdn.microsoft.com/en-us/library/system.datetime.aspx

月最后一天:

DateTime today = DateTime.Now;
DateTime lastDayOfMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));

年尾日:

DateTime today = DateTime.Now;
DateTime lastDayOfYear = new DateTime(today.Year, 12, 31);