C#中的DateTime当前月份

时间:2014-10-22 08:40:43

标签: c# datetime

相当一个noob问题,但我对如何简化此代码并使其效率感到困惑。

我试图从CURRENT月份而不是当天的月份(DateTime.Today)获得前3个月

这是我的代码:

public int NumberTicketsThreeMonthsAgo
{
    get { return AllTickets.Count(t => DateTime.Today.AddMonths(-3) < t.CreateDateTime); }
}

谢谢:)

7 个答案:

答案 0 :(得分:1)

这可能会给出正确的逻辑:

public int NumberTicketsThreeMonthsAgo
{
    DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month,
                                        1).AddMonths(-3);
    get { return AllTickets.Count(t => dt < t.CreateDateTime); }
}

答案 1 :(得分:0)

试试这个:

public int NumberTicketsThreeMonthsAgo
{
    get 
    {
        var earliestDate = new DateTime(DateTime.Today.Year, 
                                        DateTime.Today.Month,
                                        1).AddMonths(-3);
        return AllTickets.Count(t => earliestDate < t.CreateDateTime); 
    }
}

答案 2 :(得分:0)

public int NumberTicketsThreeMonthsAgo
{
    get { AllTickets.Count(t => t > new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-3)); }
}

答案 3 :(得分:0)

我会将您的新日期存储为变量并将其传入,而不是多次评估它,并将其从属性更改为方法

public int NumberTicketsThreeMonthsAgo(IEnumerable<Ticket> tickets)
{
    var startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-3);
    return tickets.Count(t => startDate < t.CreateDateTime);
}

答案 4 :(得分:0)

我想你想要一个与DateTime.Today类似的功能,但是一个返回给定DateTime的第一天的方法。您可以使用此extension method

public static DateTime MonthDayOne(this DateTime date)
{
    return new DateTime(date.Year, date.Month, 1);
}

现在这个工作并返回七月一日:

DateTime threeMonthsAgo = DateTime.Now.AddMonths(-3).MonthDayOne();

答案 5 :(得分:-1)

试试这个

 public int NumberTicketsThreeMonthsAgo
 {
     get 
     {
         new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-3)
     }
 }

答案 6 :(得分:-2)

我不清楚,但我认为这是你想要的,

MessageBox.Show("" + System.DateTime.Now.AddMonths(-3).Month);