C# DateTime

DateTime class handles date and time.

using System;
DateTime dt = new DateTime();
DateTime dt2 = new DateTime(int year, int month, int day);
DateTime dt3 = new DateTime(int year, int month, int day, int hour, int minute, int second);
DateTime dt4 = new DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);

Add date and time:
DateTime dt = new DateTime(2050, 4, 28);
TimeSpan ts = new TimeSpan(45,0,0,0);
dt = dt.Add(ts); //6/12/2050 12:00:00 AM
dt = dt.AddDays(-45); //4/28/2050 12:00:00 AM
dt = dt.AddHours(4); //4/28/2050 4:00:00 AM
TimeSpan ts2 = dt2.Subtract(dt);
ts2.ToString(); //13281.20:00:00

Compare two times.
DateTime dt2 = new DateTime(2086, 9, 8);
int d = dt.CompareTo(dt2); //-1

Some useful properties:
dt.DayOfWeek.ToString(); //Thursday
dt.Day.ToString(); //28
dt.ToShortTimeString(); //4:00 AM



endmemo.com © 2024  | Terms of Use | Privacy | Home