开发者

Convert Time to decimal in C#

what i need to do, is have two defined strings that is inputted by the user,

string in = "9:35"; //am
string out = "11:55"; //am

and i need to subtract them, so that would get the total hours that they were signed in. which should equal:

string total = "2:20"

开发者_JAVA百科then, i need to convert that into a decimal.. so, 2:20 would be

string decimal = "2.33";

I dont know how to do that, any help would be appreciated!

P.S: id also like to be able to calculate the total hours they were checked in from a decimal number, so basically the opposite


DateTime dt1 = DateTime.Parse("11:55");    
DateTime dt2 = DateTime.Parse("9:35");

double span = (dt1 - dt2).TotalHours;

Do you actually need the "2:20" or is that just an intermediate step?

Edit: If you wanted to go back, you'd just need to do a little bit of math. Take the remainder of the decimal and multiply by 60, then round. Those will be the minutes, so just add them to the hours.


Or you could do like this:

decimal dec = Convert.ToDecimal(TimeSpan.Parse("11:30").TotalHours);
// returns:  11.5


I know this is a very old post, but its the first that comes up in Google when looking for ways to convert hours and minutes to decimal hours.

None of these answers work when dealing with more than 24 hours (eg, when dealing with hours in a pay period). I handled the conversion like this:

string HoursWorkedThisWeek = "50:08" 
//50 hours and 8 minutes
string[] a = HoursWorkedThisWeek.Split(new string[] { ":" }, StringSplitOptions.None);
//a[0] contains the hours, a[1] contains the minutes
decHours = Math.Round(Convert.ToDecimal(a[0]) + (Convert.ToDecimal(a[1]) / 60), 2); 
//Result is 50.13


How about this?

TimeSpan inTime = new TimeSpan(9, 35, 0); //or TimeSpan.Parse("9:35");
TimeSpan outTime = new TimeSpan(11, 55, 0); //or TimeSpan.Parse("11:55");

TimeSpan total = outTime - inTime;

decimal timevalue = total.Hours + (total.Minutes > 0 ? total.Minutes/60 : 0);

string totalString = timevalue.ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜