计算给定日期的季度的开始日期和名称

时间:2009-09-29 11:52:57

标签: c# date

如何找到指定日期四分之一的开始日期和名称(1,2,3等)?

7 个答案:

答案 0 :(得分:103)

像(未经测试)的东西:

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);

答案 1 :(得分:5)

int GetQuarterName(DateTime myDate)
{
    return (int)Math.Ceiling(myDate.Month / 3.0);
}

DateTime GetQuarterStartingDate(DateTime myDate)
{
    return new DateTime(myDate.Year,(3*GetQuarterName(myDate))-2,1);
}

GetQuarterName获取当前月份数/ 3的“下一个”整数值。

GetQuarterStartingDate使用GetQuarterName的输出计算月份值,原始日期的年份部分,以及1表示要返回的月份的第一天。

(道歉没有意义,我有流感。:()

答案 2 :(得分:2)

https://msdn.microsoft.com/ru-ru/library/ms127415(v=vs.110).aspx

using Microsoft.VisualBasic;
var quarter = DateAndTime.DatePart(DateInterval.Quarter, (DateTime)dateTimePickerDateTime.Value);

答案 3 :(得分:0)

更简单的两个班轮,带有现场演示 here +按 F8 即可运行。

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 

如果您正在查看本季度的最后一天,请使用 DateTime.DaysInMonth

var endDateInQtr = new DateTime(date.Year, totalMonths, DateTime.DaysInMonth(date.Year, totalMonths));

答案 4 :(得分:0)

我认为此解决方案会很好地工作。它占用更多的线路,总线非常冗长! `

private DateTime GetFirstDayOfYearlyQuarter(DateTime value)
{
    switch (value.Month)
    {
        case 1:
        case 2:
        case 3:
            return new DateTime(value.Year, 1, 1);
        case 4:
        case 5:
        case 6:
            return new DateTime(value.Year, 4, 1);
        case 7:
        case 8:
        case 9:
            return new DateTime(value.Year, 7, 1);
        case 10:
        case 11:
        case 12:
            return new DateTime(value.Year, 10, 1);
        default:
            throw new Exception(@"¯\_(ツ)_/¯");
    }
}

`

P.S。这只会找到季度的第一天,但​​是您可以轻松地将其扩展为季度的数量,等等。

答案 5 :(得分:0)

    public static class DateTimeExtensions
{
    public static DateTime StartOfQuarter(this DateTime _date)
    {
        var quarter = decimal.ToInt16(Math.Ceiling(_date.Month / 3.0m));
        return new DateTime(_date.Year, quarter, 1);
    }
}

使用

var quarterStart = DateTime.Today.StartOfQuarter();

答案 6 :(得分:0)

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);