Click here to Skip to main content
15,886,094 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a table that has int datatype to save 4 digits that represent for HHmm. I fetch 4 digits from database, and returns to me in this plain format 1130, no colon between 11 and 30 and no AM or PM. After that, I want to compare with HHmm from today datetime's components in 'if statement', and below are codes.

I fetched 4digits from table as below by creating datatable.

C#
int sTime = Convert.ToInt32(dr["SendTime"].ToString())


It returns as 1130

Then, I called today datetime and formatted as HHmm like this.
C#
DateTime TodayHrMin = DateTime.Now; //Get today's date and time
string todayHourMin = TodayHrMin.ToString("HHmm"); //Convert today's date and time to string format
int iHourMin = Convert.ToInt32(todayHourMin);//convert to int so that it can compare with int sTime


When I compare these two values (sTime and iHourMin) in if statement and do some action, it is not doing any action in if statement. Is there a way to solve this by using proper date and time formatting. I started learning asp .net a few months ago and not so much experienced in writing codes.. Thank.
Posted

Wrong approach. Don't manipulate strings representing data, manipulate data. Don't compare strings, don't compare integers representing time, compare the objects of System.DateTime type. Try to avoid using strings, but if some data comes from strings, parse it first, and then compare.
Please see all the methods named Parse, ParseExact, TryParse and TryParseExact:
http://msdn.microsoft.com/en-us/library/system.datetime%28v=vs.110%29.aspx[^].

For comparison, use the operators defined for this type: '==', '>=', '<=', '<', '>', '-'.

—SA
 
Share this answer
 
DateTime has properties to get its Hour and Minute values.

Why don't you try this?

CSS
int DBTime = 1130;


//Parse DB Hour and Minute
int hour = DBTime / 100;
int minute = DBTime % 100;

DateTime TodayHrMin = DateTime.Now; //Get today's date and time
int todayHour = TodayHrMin.Hour; //today's Hour
int todayMinute = TodayHrMin.Minute; //today's Minute

//TODO: Your Logic


or you can do it in the other way:

C#
DateTime TodayHrMin = DateTime.Now; //Get today's date and time

int todayHour = TodayHrMin.Hour; //today's Hour
int todayMinute = TodayHrMin.Minute; //today's Minute

//Parse DB Hour and Minute
int TodayDBFormattedTime = (todayHour * 100) + todayMinute;

//TODO: Your Logic
 
Share this answer
 
v2
Comments
Member 10858162 30-Aug-14 22:14pm    
Thank alot.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900