C#中将时间转换为十进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1834271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Time to decimal in C#
提问by Xavier
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"
then, i need to convert that into a decimal.. so, 2:20 would be
然后,我需要将其转换为十进制.. 所以,2:20 将是
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
PS:id 也喜欢能够从十进制数计算他们签到的总小时数,所以基本上相反
采纳答案by Brandon
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?
你真的需要“2:20”还是只是一个中间步骤?
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.
编辑:如果你想回去,你只需要做一点数学。取小数的余数乘以60,然后四舍五入。这些将是分钟,所以只需将它们添加到小时。
回答by Bob
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();
回答by Rasmus
Or you could do like this:
或者你可以这样做:
decimal dec = Convert.ToDecimal(TimeSpan.Parse("11:30").TotalHours);
// returns: 11.5
回答by Tim
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.
我知道这是一篇很老的帖子,但它是第一个在 Google 中寻找将小时和分钟转换为十进制小时的方法时出现的。
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:
在处理超过 24 小时的工作时(例如,处理支付期内的工作时间),这些答案都不起作用。我这样处理转换:
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