The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 through 11:59:59 P.M., December 31, 9999 in the Gregorian calendar. An inbuilt structure you can use to manipulate dates is called DateTime.
The default date format is UK format (day/month/year hours: minutes: seconds)
DateTime d = DateTime.Now; //display system date and time
DateTime d = DateTime.Today; //display system date, and time 00:00:00.
The following table describes the custom date and time format specifiers.
d – dd/mm/yyyy 20/02/2015
dd – date 20
ddd - day fri
dddd – full day Friday
f or F– Full date/time pattern Friday, February 20, 2015 3:42 pm
ff or FF- The hundredths of a second
fff or FFF- The milliseconds
ffff or FFFF- The ten thousandths of a second
fffff or FFFFF
ffffff or FFFFFF
fffffff or FFFFFFF
D - Friday, February 20, 2015
g – General date/time pattern 20/02/2015 3:42 pm
hh - The hour, using a 12-hour format
HH - The hour, using a 24-hour format
m – February 20, 2015
mm – The minute, from 00 through 59. – 42
MM - The month, from 01 through 12. 02
MMM - The abbreviated name of the month – feb
MMMM - The full name of the month. – February
ss - The second, from 00 through 59. – 51
t - time – 3:42 pm
T – Time – hh:mm:ss AM/PM
tt – am/pm
yy - The year, from 00 to 99. – 15
yyyy - The year as a four-digit number. 2015
now.ToLongDateString() // Equivalent to D
now.ToLongTimeString() // Equivalent to T
now.ToShortDateString() // Equivalent to d
now.ToShortTimeString() // Equivalent to t
The date and time methods:
DateTime.Now.AddDays(1)
DateTime.Now.AddHours(1)
DateTime.Now.AddMilliseconds(1)
DateTime.Now.AddMinutes(1)
DateTime.Now.AddMonths(1)
DateTime.Now.AddSeconds(1)
DateTime.Now.AddYears(1)
int diff = d2.CompareTo(d1); //return -1, 0, 1
int diff = DateTime.Compare(d2,d1); //return -1, 0, 1
DateTime.DaysInMonth(2015, 2)
DateTime.Equals(d1,d2)
DateTime.IsLeapYear(2001)
Example: 1
private void button1_Click(object sender, EventArgs e)
{
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddMonths(2);
TimeSpan d3 = d2.Subtract(d1);
label1.Text = DateTime.Now.Subtract(d3).ToString();
}
Example: 2
private void button1_Click(object sender, EventArgs e)
{
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddMonths(2);
TimeSpan d3 = d2-d1;
label1.Text = (d1-d3).ToString();
}