Luat
Luat

Reputation: 53

How to convert from HH:MM:SS to hour decimal?

i have a string like this

currentTime = String.Format("{0:00}:{1:00}:{2:00}",ts.Hours, ts.Minutes, ts.Seconds);

How do i convert it to hour in decimal? For example : 00:30:00 = 0.5 hour Thank you.

Upvotes: 1

Views: 1957

Answers (2)

aloisdg
aloisdg

Reputation: 23521

Use TimeSpan.TotalHours. MSDN:

Gets the value of the current TimeSpan structure expressed in whole and fractional hours.

using System;

public class Example
{
   public static void Main()
   {
      // Define an interval of 1 day, 15+ hours.
      TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); 
      Console.WriteLine("Value of TimeSpan: {0}", interval);

      Console.WriteLine("{0:N5} hours, as follows:", interval.TotalHours);
      Console.WriteLine("   Hours:        {0,3}", 
                        interval.Days * 24 + interval.Hours);
      Console.WriteLine("   Minutes:      {0,3}", interval.Minutes);
      Console.WriteLine("   Seconds:      {0,3}", interval.Seconds);
      Console.WriteLine("   Milliseconds: {0,3}", interval.Milliseconds);
   }
}
// The example displays the following output:
//       Value of TimeSpan: 1.15:42:45.7500000
//       39.71271 hours, as follows:
//          Hours:         39
//          Minutes:       42
//          Seconds:       45
//          Milliseconds: 750

Example with your code

using System;

public class Program
{
    public static void Main()
    {
        var now = DateTime.Parse("00:30:00");
        var ts = now.TimeOfDay; // ts is your timespan
        Console.WriteLine(ts.TotalHours); // will print 0.5
    }
}

Try it online!

TotalHours is a double (which is a kind of decimal). If you want a decimal because you need a decimal, you can do (decimal)ts.TotalHours. Before doing so, take the time to look online the difference between double and decimal to see if you really need a decimal.

Upvotes: 1

haldo
haldo

Reputation: 16701

You can use TotalHours which gives a the time in hours as a double. You can just cast it to decimal.

decimal hours = (decimal) ts.TotalHours;

Upvotes: 0

Related Questions