Method of getting the start and end times of last month from the DateTime function of.NET

  • 2021-06-28 09:06:56
  • OfStack

This article gives an example of how the DateTime function of.NET can get the start and end times of the previous month.Share it for your reference.Specific analysis is as follows:

A common headache encountered in reports is the need to automatically select data from the past month as the current report output.Some examples of C# from.NET have been queried on the internet, and it is found that the implementation is quite complex. In fact, this problem can be easily solved by the DateTime function of.NET, because the NET provides us with the current number of days--System.DateTime.Now.Day function, as well as the AddDays and AddMonth functions that add days and months.

So we can imagine that the current time - the current day = the end of last month, and the current time - a month - the current day + 1 = the start time of last month

Then?

Starting time of last month:

lastMonthBegin = DateTime.Now.AddMonths(-1).AddDays(1-DateTime.Now.Day);


Last month to time:
lastMonthEnd = DateTime.Now.AddDays(-DateTime.Now.Day)

Be accomplished!!

I hope that the description in this paper will be helpful to your.NET program design.


Related articles: