C Method for getting the start and end dates of each year month and week

  • 2021-12-05 07:01:51
  • OfStack

This article illustrates how C # obtains the start and end dates of each year, month, and week. Share it for your reference, as follows:

When we write programs, we often have to calculate the start date and end date of year, month and week. Here, we give the solution method of Unification 1


/// <summary>
///  Declare duration type enumeration 
/// </summary>
public enum Period {Day, Week, Month, Year};
/// <summary>
///  Gets the start and end dates of the specified period 
/// </summary>
/// <param name="period"> Period type </param>
/// <param name="beginDate"> Start date </param>
/// <param name="endDate"> End date </param>
public static void GetPeriod(Period period, out DateTime beginDate, out DateTime endDate)
{
  int year = DateTime.Today.Year;
  int month = DateTime.Today.Month;
  switch (period)
  {
    case Period.Year: // Year 
      beginDate = new DateTime(year, 1, 1);
      endDate = new DateTime(year, 12, 31);
      break;
    case Period.Month: // Month 
      beginDate = new DateTime(year, month, 1);
      endDate = beginDate.AddMonths(1).AddDays(-1);
      break;
    case Period.Week: // Week 
      int week = (int)DateTime.Today.DayOfWeek;
      if (week == 0) week = 7; // Sunday 
      beginDate = DateTime.Today.AddDays(-(week - 1));
      endDate = beginDate.AddDays(6);
      break;
    default: // Day 
      beginDate = DateTime.Today;
      endDate = DateTime.Today;
      break;
  }
}

PS: Here are some date and time related tools for your reference:

Date Days Difference Calculator:
http://tools.ofstack.com/jisuanqi/onlinedatejsq

Online date calculator/difference days calculator:
http://tools.ofstack.com/jisuanqi/datecalc

Online date/day calculator:
http://tools.ofstack.com/jisuanqi/date_jisuanqi

Online lunar/solar calendar conversion tool:
http://tools.ofstack.com/bianmin/yinli2yangli

Online Days Calculator (flash version):
http://tools.ofstack.com/jisuanqi/datejsq

For more readers interested in C # related content, please check the topics on this site: "C # Date and Time Operation Skills Summary", "C # String Operation Skills Summary", "C # Array Operation Skills Summary", "XML File Operation Skills Summary in C #", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial" and "C # Object-Oriented Programming Introduction Tutorial"

I hope this article is helpful to everyone's C # programming.


Related articles: