1

I'm working on a code which has a logic but I'm unable to compare to them using if can any one please help.

This I have a logic I global.aspx

string sTime = System.Configuration.ConfigurationManager.AppSettings["StartTime"].ToString();
string eTime = System.Configuration.ConfigurationManager.AppSettings["EndTime"].ToString();
DateTime s = DateTime.Parse(sTime);//here i'm getting an Exception while debugging
DateTime e = DateTime.Parse(eTime);
DateTime nTime = DateTime.Now;
if (nTime >= s || nTime < s)
{
    InvokeUnderMaintenance();
}

Exception

System.FormatException was unhandled by user code
HResult=-2146233033 Message=String was not recognized as a valid DateTime. Source=mscorlib StackTrace: at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s) at EsiTrak.Web.MvcApplication.Application_PostAuthenticateRequest() in C:\Project\EsitrakWebEnablement\EsiTrak.Web\Global.asax.cs:line 138
InnerException:

message::An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

This I have taken in webconfig file as time starttime and end time values

<add key="StartTime" value="12"/>
<add key="EndTime" value="18"/>

Can any one tell me how to comapre start time and end time with current time using || operator or && operator?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Aakib13
  • 33
  • 4
  • 3
    `12` and `18` are not valid datetime values. It should be like `dd.mm.yyyy hh:MM:ss` – Backs Jan 31 '20 at 06:42
  • values of `StartTime` and `EndTime` should be in proper date format. `12` and `18` are hours? if yes then do you want to check date as well? – Prasad Telkikar Jan 31 '20 at 06:43
  • They don't includes "enough" information to parse a `DateTime`. I strongly suspect that you need to parse `TimeSpan` instead which can be store time of day. – Soner Gönül Jan 31 '20 at 06:44
  • Does this answer your question? [Find if current time falls in a time range](https://stackoverflow.com/questions/1504494/find-if-current-time-falls-in-a-time-range) – vikscool Jan 31 '20 at 06:56

1 Answers1

2

You are parsing an integer, which is not of a datetime format. So parse can't identify the format.

If you want to compare with the hours, you can do it as follows:

var startHour = Int32.Parse(sTime);
var endHour = Int32.Parse(eTime);
if (nTime.Hour >= startHour && nTime.Hour < eTime)
{
    InvokeUnderMaintenance();
}

You can then remove the datetime parse altogether.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61