CSharp - DateTime DateTimeOffset Calculation

Introduction

DateTime and DateTimeOffset provide a similar set of instance properties that return various date/time elements:

Demo

using System;
class MainClass{/* w  w w  .  j a va  2  s.c o m*/
   public static void Main(string[] args){
         DateTime dt = new DateTime (2000, 2, 3,
                                     10, 20, 30);

         Console.WriteLine (dt.Year);         // 2000
         Console.WriteLine (dt.Month);        // 2
         Console.WriteLine (dt.Day);          // 3
         Console.WriteLine (dt.DayOfWeek);    // Thursday
         Console.WriteLine (dt.DayOfYear);    // 34

         Console.WriteLine (dt.Hour);         // 10
         Console.WriteLine (dt.Minute);       // 20
         Console.WriteLine (dt.Second);       // 30
         Console.WriteLine (dt.Millisecond);  // 0
         Console.WriteLine (dt.Ticks);        // 630851700300000000
         Console.WriteLine (dt.TimeOfDay);    // 10:20:30  (returns a TimeSpan)
   }
}

Result

DateTimeOffset also has an Offset property of type TimeSpan.

Both types provide the following instance methods to perform computations

  • AddYears
  • AddMonths
  • AddDays
  • AddHours
  • AddMinutes
  • AddSeconds
  • AddMilliseconds
  • AddTicks

These all return a new DateTime or DateTimeOffset, and they take into account such things as leap years.

You can pass in a negative value to subtract.

Add method adds a TimeSpan to a DateTime or DateTimeOffset. The + operator is overloaded to do the same job:

Demo

using System;
class MainClass//from   www  .ja va  2s  . c  o  m
{
   public static void Main(string[] args)
   {
         DateTime dt = new DateTime (2000, 2, 3,
                                     10, 20, 30);

         TimeSpan ts = TimeSpan.FromMinutes (90);
         Console.WriteLine (dt.Add (ts));
         Console.WriteLine (dt + ts);    
   }
}

Result

You can subtract a TimeSpan from a DateTime/DateTimeOffset and subtract one DateTime/DateTimeOffset from another.

The latter gives you a TimeSpan:

Demo

using System;
class MainClass/*  www.  jav  a  2 s .  c om*/
{
   public static void Main(string[] args)
   {
         DateTime thisYear = new DateTime (2015, 1, 1);
         DateTime nextYear = thisYear.AddYears (1);
         TimeSpan oneYear = nextYear - thisYear;
         Console.WriteLine(oneYear);
   }
}

Result