Working with DateTime Data ISYS 350
Declare DateTime Variable Example: DateTime mydate; Convert date entered in a textbox to DateTime data: Use Convert: mydate = Convert.ToDateTime(textBox1.Text); Use DateTime class Parse method: mydate = DateTime.Parse(textBox1.Text); DateTime variable’s properties and methods: MinValue, MaxValue Year, month,DayOfWeek, hour, etc. AddYear,AddDays,AddHours, etc. Subtract ToLongDateString, ToShortDateString
DateTime Example DateTime myDate; myDate = DateTime.Parse(textBox1.Text); MessageBox.Show(myDate.ToLongDateString()); MessageBox.Show(DateTime.MinValue.ToShortDateString()); MessageBox.Show(DateTime.MaxValue.ToShortDateString());
How to calculate the number of days between two dates? TimeSpan class: TimeSpan represents a length of time. Define a TimeSpan variable: TimeSpan ts; We may use a TimeSpan class variable to represent the length between two dates: ts = laterDate-earlierDate;
Code Example DateTime earlierDate, laterDate; double daysBetween; TimeSpan ts; earlierDate = DateTime.Parse(textBox1.Text); laterDate = DateTime.Parse(textBox2.Text); ts = laterDate-earlierDate; daysBetween = ts.Days; MessageBox.Show("There are " + daysBetween.ToString() + " days between " + earlierDate.ToShortDateString() + " and " + laterDate.ToShortDateString()); Note: Pay attention to how we create the output string.
Useful Properties and Method Get current date: DateTime thisDate=DateTime.Today; Get current date and time: DateTime thisDate=DateTime.Now; Calculate # of days between two dates: myDate = DateTime.Parse(textBox1.Text); DaysBetween = thisDate.Subtract(myDate).Days;
Three Methods to Compute Age Given DOB: 1. Using Subtract method 2 Three Methods to Compute Age Given DOB: 1. Using Subtract method 2. Using Year property 3. Using TimeSpan Days DateTime myDate, thisDate = DateTime.Today; double Age; myDate = DateTime.Parse(textBox1.Text); Age = (thisDate.Subtract(myDate).Days / 365); MessageBox.Show(Age.ToString()); Age = thisDate.Year - myDate.Year; TimeSpan ts; ts = thisDate - myDate; Age = ts.Days / 365;
Compute Age Given DOB: Age<30, Young 30<=Age<65, Middle Age>=65, Old DateTime myDate, thisDate=DateTime.Today; double Age; myDate = DateTime.Parse(textBox1.Text); Age = (thisDate.Subtract(myDate).Days / 365); MessageBox.Show(Age.ToString()); If (Age<30) MessageBox.Show(“Young”); elseif (Age<65) MessageBox.Show(“Middle”); else MessageBox.Show(“Old”);
Date Comparison DateTime thisDate, currentDate = DateTime.Today; thisDate = DateTime.Parse(textBox1.Text); if (currentDate>thisDate) MessageBox.Show("after"); else MessageBox.Show("before");