Some useful C# DateTime handy code sample

satinder singh / Updated : / 0 Comments

  Here in this article we will play with DateTime in our C# application. Basically, a handful easy code to get today’s date, yesterday’ date, current week start current weekend date etc and many more.

C# DateTime Code


DateTime baseDate = DateTime.Today;

var today = baseDate;
var yesterday = baseDate.AddDays(-1);
var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
var lastWeekStart = thisWeekStart.AddDays(-7);
var lastWeekEnd = thisWeekStart.AddSeconds(-1);
var thisMonthStart = baseDate.AddDays(1 - baseDate.Day);
var thisMonthEnd = thisMonthStart.AddMonths(1).AddSeconds(-1);
var lastMonthStart = thisMonthStart.AddMonths(-1);
var lastMonthEnd = thisMonthStart.AddSeconds(-1);

Here’s the code to display last month start date, end date etc.


Post Comment


Your email address will not be published. Required fields are marked *