Posts Tagged Date Range

.Net C Sharp Date Range Check Method

This function is a trivial example of how to do a basic date range check in .Net. I do a few silly conversions from string to timestamp only to serve as an example.

View Code CSHARP
/*
Assumes the local culture.  
Does a check to see if the current time is within the range 
  of 7 AM and 1 PM.  If so, returns true.
*/
if (IsCurrentDateInRange("7:00", "13:00")) {
   //The current date is in range.
} else {
  //The current date is out of range.
}
View Code CSHARP
using System;
/*
startTime should be in the format HH:mm such as 09:45
endTime should be in the format HH:mm such as 18:45
The culture is assumed to be the local one which can be 
troubling in applications that extend themselves internationally.
*/
public bool IsCurrentDateInRange(string startTime, string endTime) {
  DateTime dtNow = DateTime.Now;
  DateTime dtStart, dtEnd;
  int hour = 0, minute = 0;
 
  string[] strDt = startTime.Split(new char[] { ':' });
  if (strDt.Length > 1)
  {
     Int32.TryParse(strDt[0], out hour);
     Int32.TryParse(strDt[1], out minute);
 
     dtStart = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day, hour, minute, 0);
  }
  else
  {
     //TODO: log an error in formatting.
     return false;
  }               
 
  strDt = endTime.Split(new char[] { ':' });
  if (strDt.Length > 1)
  {
     hour = minute = 0;
     Int32.TryParse(strDt[0], out hour);
     Int32.TryParse(strDt[1], out minute);
 
     dtEnd = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day, hour, minute, 0);
  }
  else
  {
     //TODO: log an error in formatting.
    return false;
  }
 
  TimeSpan tsEndDiff = dtEnd - dtNow;
  TimeSpan tsStartDiff = dtNow - dtStart;
  if (tsStartDiff.TotalSeconds >= 0 && tsEndDiff.TotalSeconds >= 0)
  {
     return true;
  }
  else 
     return false;
}

, , ,

No Comments