Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have string is like("+5" or "-5"). and i want to add it into Hours of Datetime.

i.e.Time is 01:20:20 PM and string="+5" then output will be : 06:20:20 PM
Time is 01:20:20 PM and string="-5" then output will be : 08:20:20 AM

Suggest me solution for this one.

Thanks
Posted
Updated 9-Dec-11 3:37am
v2

Use the TimeSpan class.

Here[^] is more information on TimeSpan.Add method.
 
Share this answer
 
Comments
fjdiewornncalwe 9-Dec-11 10:15am    
This might be a little overkill because of the DateTime.AddHours method.
Sergey Alexandrovich Kryukov 9-Dec-11 15:14pm    
Yes, just a little, but good to know as a more universal approach, so I voted 5.
--SA
Abhinav S 9-Dec-11 22:30pm    
Thanks SA.
C#
DateTime dt = DateTime.Now;
String s = "+5";    // or "-5" works with both + and -
dt  = dt.AddHours(Convert.ToInt32(s));
 
Share this answer
 
v3
Comments
KIDYA 10-Dec-11 1:22am    
Throws an exception- input string is not in correct format
Derek Henderson 12-Dec-11 8:42am    
Not on my system running VS2010 . Works a treat.
Try this:

C#
DateTime clientTime = System.Date.Now;
string hrsToCompute = "+5";
int final = 0;

if(hrsToCompute.IndexOf("+"))
{
   final = Convert.ToInt32(hrsToCompute.Substring(1));
   clientTime.AddHours(hours);
}
//same logic here for negative.....


Regards,
Eduard
 
Share this answer
 
Comments
fjdiewornncalwe 9-Dec-11 10:15am    
Close, but I would update your .Substring(1) to .Substring( hrsToCompute.IndexOf("+") + 1 ).
I have a personal pet-peeve on using fixed indices for things.

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