using System; class MainClass { public static void Main() { DateTime dt = new DateTime(1900, 2, 29); } }
Author: coder
DateTime Now and its calculation
using System; class MainClass { public static void Main() { TimeSpan timespan1 = new TimeSpan(2, 12, 0, 0); TimeSpan timespan2 = new TimeSpan(4, 12, 0, 0); TimeSpan oneWeek = timespan1 + timespan2; DateTime now = DateTime.Now; DateTime past = now - oneWeek; DateTime future = now + oneWeek; Console.WriteLine("Now : {0}", now); Console.WriteLine("Past : {0}", past); Console.WriteLine("Future: {0}", future); } }
Parse and ParseExact
using System; class MainClass { public static void Main(string[] args) { DateTime dt1 = DateTime.Parse("Sep 2005"); Console.WriteLine(dt1); DateTime dt2 = DateTime.Parse("Monday 5 September 2005 14:15:33"); Console.WriteLine(dt2); DateTime dt3 = DateTime.Parse("5, 9,05"); Console.WriteLine(dt3); DateTime dt4 = DateTime.Parse("5/9/2005 14:15:33"); Console.WriteLine(dt4); DateTime dt5 = DateTime.Parse("2:15 PM"); Console.WriteLine(dt5); DateTime dt6 = DateTime.ParseExact("2:13:30 PM", "h:mm:ss tt", null); Console.WriteLine(dt6); DateTime dt7 = DateTime.ParseExact("Mon, 05 Sep 2005 14:13:30 GMT","ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", null); Console.WriteLine(dt7); DateTime dt8 = DateTime.ParseExact("September 05", "MMMM dd", null); Console.WriteLine(dt8); } }
comparisons between DateTime objects
using System; using System.Globalization; class MainClass { public static void Main() { // Create some date/time objects DateTime dt = new DateTime(); DateTime dt1 = new DateTime(2001, 12, 31); DateTime dt2 = new DateTime(2000, 12, 31, 23, 59, 59); if (dt2 < dt1) Console.WriteLine("Dt2 < Dt1"); else if (dt2 == dt1) Console.WriteLine("Dt2 == Dt1"); else Console.WriteLine("Dt2 > Dt1"); } }
Constructors of DateTime
using System; using System.Globalization; class MainClass { public static void Main() { DateTime dt = new DateTime(); DateTime dt1 = new DateTime(2001, 12, 31); DateTime dt2 = new DateTime(2000, 12, 31, 23, 59, 59); // Print them out as strings Console.WriteLine("DT as string: {0}", dt.ToString()); Console.WriteLine("DT1 as string: {0}", dt1.ToString()); Console.WriteLine("DT2 as string: {0}", dt2.ToString()); } }
Add TimeSpan to DateTime
using System;
using System.Globalization;
class MainClass {
public static void Main() {
DateTime dt = new DateTime();
DateTime dt1 = new DateTime(2001, 12, 31);
DateTime dt2 = new DateTime(2000, 12, 31, 23, 59, 59);
TimeSpan year = new TimeSpan(365 * TimeSpan.TicksPerDay);
for (int i = 0; i < 10; ++i) dt += year; Console.WriteLine("DT as string: {0}", dt.ToString()); } } [/csharp]
Output DateTime object
using System; using System.Globalization; public class DatesApp { public static void Main(string[] args) { DateTime dt = DateTime.Now; Console.WriteLine(dt); Console.WriteLine("date = {0}, time = {1} ",dt.Date, dt.TimeOfDay); } }