DateTime and DateTimeOffset provide a similar set of instance properties that return various date/time elements:
using System; class MainClass{//from ww w .j av a 2s.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) } }
DateTimeOffset also has an Offset property of type TimeSpan.
Both types provide the following instance methods to perform computations
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:
using System; class MainClass//w ww. j av a2 s . co 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); } }
You can subtract a TimeSpan from a DateTime/DateTimeOffset and subtract one DateTime/DateTimeOffset from another.
The latter gives you a TimeSpan:
using System; class MainClass//from www . j ava2 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); } }