using System; class MainClass { public static void Main() { TimeSpan myTimeSpan = new TimeSpan(1, 2, 4, 10); DateTime myDateTime6 = DateTime.Parse("1/13/2004 23:10:30"); DateTime myDateTime8 = myDateTime6 + myTimeSpan; Console.WriteLine("myDateTime6 + myTimeSpan = " + myDateTime8); } }
use the Subtract() method to subtract a TimeSpan from a DateTime
using System; class MainClass { public static void Main() { TimeSpan myTimeSpan = new TimeSpan(1, 2, 4, 10); DateTime myDateTime6 = DateTime.Parse("1/13/2004 23:10:30"); DateTime myDateTime7 = myDateTime6.Subtract(myTimeSpan); Console.WriteLine("myDateTime6.Subtract(myTimeSpan) = " + myDateTime7); } }
use the Add() method to add a TimeSpan to a DateTime
using System; class MainClass { public static void Main() { TimeSpan myTimeSpan = new TimeSpan(1, 2, 4, 10); DateTime myDateTime6 = DateTime.Parse("1/13/2004 23:10:30"); DateTime myDateTime7 = myDateTime6.Add(myTimeSpan); Console.WriteLine("myTimeSpan = " + myTimeSpan); Console.WriteLine("myDateTime6.Add(myTimeSpan) = " + myDateTime7); } }
use the Parse() method to convert strings to DateTime instances
using System; class MainClass { public static void Main() { DateTime myDateTime5 = DateTime.Parse("1/13/2004"); DateTime myDateTime6 = DateTime.Parse("1/13/2004 23:10:30"); Console.WriteLine("myDateTime5 = " + myDateTime5); Console.WriteLine("myDateTime6 = " + myDateTime6); } }
use the IsLeapYear() method to determine if a particular year is a leap year
using System; class MainClass { public static void Main() { bool boolResult = DateTime.IsLeapYear(2004); Console.WriteLine("DateTime.IsLeapYear(2004) = " + boolResult); } }
use the DaysInMonth() method to retrieve the number of days in a particular month and year
using System; class MainClass { public static void Main() { int days = DateTime.DaysInMonth(2004, 1); Console.WriteLine("DateTime.DaysInMonth(2004, 1) = " + days); } }
use the Equals() method to compare DateTime instances
using System; class MainClass { public static void Main() { DateTime myDateTime3 = new DateTime(2004, 1, 13); DateTime myDateTime4 = new DateTime(2004, 1, 14); bool boolResult = DateTime.Equals(myDateTime3, myDateTime4); Console.WriteLine("DateTime.Equals(myDateTime3,myDateTime4) = " + boolResult); boolResult = myDateTime3.Equals(myDateTime4); Console.WriteLine("myDateTime3.Equals(myDateTime4) is " + boolResult); } }