Page Stats
Visitor: 24
Visual C#.Net DateTime Control
Visual C#.Net DateTime control is use to represent date and time with values ranging from 00:00:00 (midnight), January 1, 0001 through 11:59:59 P.M, December 31, 9999 in the Gregorian calendar. The default datetime format is in UK format (day/month/year hours:minutes:seconds).
To display system date and time write the following code:
label1.Text = DateTime.Now.ToString(); //display system date and time label1.Text = DateTime.Today.ToString(); //display system date and time(12:00:00 AM).
Format | Output |
---|---|
d | Display date in format dd/mm/yyyy eg. 15/08/2020 |
dd | Display date eg. 15 |
ddd | Display day eg. sat |
dddd | Display full day eg. Saturday |
f or F |
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();
}