Calculate the start-date and name of a quarter from a given date

前端 未结 8 1387
一向
一向 2020-12-23 14:07

How can I find the start-date and name (1, 2, 3, etc.) of a quarter from a given date?

相关标签:
8条回答
  • 2020-12-23 14:34

    Something like (untested):

    DateTime date;
    int quarterNumber = (date.Month-1)/3+1;
    DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber-1)*3+1,1);
    DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
    
    0 讨论(0)
  • 2020-12-23 14:35

    A simpler two liner with live demo here + press F8 to run .

    var date = DateTime.Now; //Give you own DateTime
    int offset = 2, monthsInQtr = 3;
    
    var quarter = (date.Month + offset) / monthsInQtr; //To find which quarter 
    var totalMonths = quarter * monthsInQtr;
    
    var startDateInQtr = new DateTime(date.Year, totalMonths - offset, 1); //start date in quarter 
    

    If you are looking at last day of the quarter use DateTime.DaysInMonth

    var endDateInQtr = new DateTime(date.Year, totalMonths, DateTime.DaysInMonth(date.Year, totalMonths));
    
    0 讨论(0)
提交回复
热议问题