1

I am working with dates in C# and need to calculate some further dates. Taking the current datetime.

How can I get the following values?

  • end of day
  • end of month
  • end of year
spajce
  • 7,044
  • 5
  • 29
  • 44
amateur
  • 43,371
  • 65
  • 192
  • 320

3 Answers3

9

If by end of ... you mean 12:59:59.999PM at that day then:

  • end of day

    var today = DateTime.Today;
    var endOfDay = new DateTime(
        today.Year, 
        today.Month,
        today.Day,
        23,
        59,
        59,
        999
    );
    
  • end of month

    var today = DateTime.Today;
    var endOfMonth = new DateTime(
        today.Year, 
        today.Month,
        DateTime.DaysInMonth(today.Year, today.Month),
        23,
        59,
        59,
        999
    );
    
  • end of year

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

If you mean something else, then explain what you mean.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

For end of month

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

see How can I get the last day of the month in C#?

For end of year

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

For end of day, assuming the end of day is close of business at 5 PM

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

See more about datetime at http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Community
  • 1
  • 1
unlimit
  • 3,672
  • 2
  • 26
  • 34
0

Last day of month:

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

Last day of year:

DateTime today = DateTime.Now;
DateTime lastDayOfYear = new DateTime(today.Year, 12, 31);
Ben Narube
  • 448
  • 3
  • 10