views:

167

answers:

3

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="time" runat="server" /> hh:mm ([time in decimal format])
<ajaxToolkit:MaskedEditExtender runat="server" Mask="99:99" TargetControlID="time" MaskType="Time" />
A: 
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;
tzaman
Thanks, so the only way is to split the value and calculate manually?
henrico
I think so; it's kind of an odd request, I don't see there being an easier way built-in.
tzaman
Ok, is there an event I can hook this calculation to in code behind, like when the user leaves the textbox (onblur)?
henrico
+4  A: 

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;
GenEric35
+1, using a `TimeSpan` is nifty.
tzaman
+1  A: 

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.

slugster
Hmm, it doesn't seem to be an OnBlur event on the <asp:textbox>
henrico
There is - but it is client side, not server side, so it isn't in your intellisense - you need to manually add it yourself: Textbox.Attributes.Add("onblur", "my javascript");
slugster