开发者

Convert time to decimals in .net

Is there an easy way to present time (hh:mm) as a decimal value? Example, 01:08 should become 1,13.

I have an asp:textbox masked (ajax) as time with the mask format "99:99". Next to this box I need to present the entered value as decimal.

<asp:TextBox ID=开发者_如何学Go"time" runat="server" /> hh:mm ([time in decimal format])
<ajaxToolkit:MaskedEditExtender runat="server" Mask="99:99" TargetControlID="time" MaskType="Time" />


You can use the TotalHours property of the TimeSpan, like this:

DateTime endHour = new DateTime(2010, 1, 2, 5, 30, 0);

double totalHours = new TimeSpan(endHour.Hour, endHour.Minute, 0).TotalHours;


First up, you might find it more appropriate to use a TimeSpan rather than a DateTime. So for your example, this:

TimeSpan t = new TimeSpan(0, 1, 8);
decimal d = t.Minutes + (t.Seconds / 60m);
Console.WriteLine(d.ToString());

produces the correct result. The m after the 60 forces that calculation to be decimal.

You can't hook this C# directly to the onblur of the textbox, as it runs server side. If you need this to run client side you will have to either use an ajax callback to evaluate it, or use javascript to cut the string up, then calculate each bit (minutes and seconds) individually, then output the result to the second textbox or label.


double decimalTime = DateTime.Now.Hour + (double)DateTime.Now.Minute/60

Edit: Better way, using GenEric's TimeSpan idea:

double hours = new TimeSpan(DateTime.Now.Hour, 
                            DateTime.Now.Minute, 
                            0).TotalHours;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜