A Real Timespan Object With .Years & .Months

后端 未结 8 2123
执念已碎
执念已碎 2020-12-05 02:51

Consider the following 2 scenarios: Scenario 1). Today is May 1st 2012, and Scenario 2). Today is September 1st 2012.

Now, consider that we write on our webpage the

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 03:20

    Using .Net 4.5 and the CultureInfo class, one can add months and years to a given date.

    DateTime datetime = DateTime.UtcNow;
    int years = 15;
    int months = 7;
    
    DateTime yearsAgo = CultureInfo.InvariantCulture.Calendar.AddYears(datetime, -years);
    DateTime monthsInFuture = CultureInfo.InvariantCulture.Calendar.AddMonths(datetime, months);
    

    Since that's a lot of typing, I prefer to create extension methods:

    public static DateTime AddYears(this DateTime datetime, int years)
    {
        return CultureInfo.InvariantCulture.Calendar.AddYears(datetime, years);
    }
    
    public static DateTime AddMonths(this DateTime datetime, int months)
    {
        return CultureInfo.InvariantCulture.Calendar.AddMonths(datetime, months);
    }
    
    DateTime yearsAgo = datetime.AddYears(-years);
    DateTime monthsInFuture = datetime.AddMonths(months);
    

提交回复
热议问题