DateTime Custom Extensions

I often see code snippets in the real-time projects which bind the DateTime data to and from input controls using if else conditions.

Eg. - The below snippet is to bind the textbox value to the custom entity on click of a Save button.

  1. var assessmentData = new AssessmentDetails();  
  2. if(!string.IsNullOrEmpty(txtReviewCompletedDate.Text))  
  3.       assessmentData.ReviewDate = Convert.ToDateTime(txtReviewCompletedDate.Text);   

In similar fashion, textbox value is assigned from the custom entity on page load.

I have created a DateTime extension utility class which will avoid these kind of null checks in all the code files and just have this checking in one place.

To assign the DateTime value to the textbox from the custom entity, below DateTime extension method can be used.
  1. public static string GetDateString(this DateTime date)   
  2. {  
  3.         return date != DateTime.MinValue ? date.ToString(Constants.Date_DisplayFormat) : string.Empty;   
  4. }    
  1. txtReviewCompletedDate.Text = assessmentData.ReviewDate.GetDateString();  
Below is the constant code from Constants.cs file,
  1. public static const string Date_DisplayFormat = "MM/dd/yyyy" 

To get the date from the textbox, the following string extension method can be used by passing the textbox value. It returns the value as DateTime if value exists, else the default value.

  1. public static DateTime GetDateFromString(this string dateString)  
  2. {  
  3.            if (!string.IsNullOrEmpty(dateString))  
  4.            {  
  5.                  DateTime result;  
  6.                  var isValidDate = DateTime.TryParse(dateString, out result);  
  7.                  return isValidDate ? result : DateTime.MinValue;                  
  8.            }  
  9.            return DateTime.MinValue;  
  10. }  

Using this option, the above said code can be written as below. 
  1. assessmentData.ReviewDate = txtReviewCompletedDate.Text.GetDateFromString();  
This way, we can avoid repeated null checks and effeciently bind the data to input control.
I have uploaded the utility helper as .zip file for download.