Home > Software engineering >  How to identify difference is more than 12 month from DateTimeOffset in C#
How to identify difference is more than 12 month from DateTimeOffset in C#

Time:02-03

I want to check how it's possible to identify the difference that is more than 12 months from DateTimeOffset.

var startDate = DateTimeOffset.Parse("08/11/2012 12:00:00");
var endDate= DateTimeOffset.Parse("08/12/2013 13:00:00");
TimSpan tt = startDate - endDate;

In the timespan, there is no option for the month or year.

CodePudding user response:

Instead of subtracting one from another to get a TimeSpan, add 12 months to the start to find out the cut-off:

if (startDate.AddMonths(12) > endDate)
{
    // ...
}

Note that you should think carefully about corner cases - in particular, what you'd want to do with a start date of February 29th...

CodePudding user response:

You can add or subtract either dates or time intervals from a particular DateTimeOffset value. Arithmetic operations with DateTimeOffset values, unlike those with DateTime values, adjust for differences in time offsets when returning a result. For example, the following code uses DateTime variables to subtract the current local time from the current UTC time. The code then uses DateTimeOffset variables to perform the same operation. The subtraction with DateTime values returns the local time zone's difference from UTC, while the subtraction with DateTimeOffset values returns TimeSpan.Zero.

using System;

public class DateArithmetic
{
   public static void Main()
   {
      DateTime date1, date2;
      DateTimeOffset dateOffset1, dateOffset2;
      TimeSpan difference;

      // Find difference between Date.Now and Date.UtcNow
      date1 = DateTime.Now;
      date2 = DateTime.UtcNow;
      difference = date1 - date2;
      Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);

      // Find difference between Now and UtcNow using DateTimeOffset
      dateOffset1 = DateTimeOffset.Now;
      dateOffset2 = DateTimeOffset.UtcNow;
      difference = dateOffset1 - dateOffset2;
      Console.WriteLine("{0} - {1} = {2}",
                        dateOffset1, dateOffset2, difference);
      // If run in the Pacific Standard time zone on 4/2/2007, the example
      // displays the following output to the console:
      //    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
      //    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM  00:00 = 00:00:00
   }
}

For more details you can read HERE

  • Related