Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
TimeSpan.FromHours() Method in C#
The TimeSpan.FromHours() method in C# is used to create a TimeSpan object that represents a specified number of hours. This static method is accurate to the nearest millisecond and provides a convenient way to create time spans based on hour values.
Syntax
Following is the syntax for the TimeSpan.FromHours() method −
public static TimeSpan FromHours(double value);
Parameters
-
value − A double that represents the number of hours. The value can be positive or negative and is accurate to the nearest millisecond.
Return Value
This method returns a TimeSpan object that represents the specified number of hours.
Using TimeSpan.FromHours() with Integer Values
The most common usage is with whole hour values −
using System;
public class Demo {
public static void Main() {
TimeSpan span1 = TimeSpan.FromHours(3);
TimeSpan span2 = TimeSpan.FromHours(12);
TimeSpan span3 = TimeSpan.FromHours(24);
Console.WriteLine("3 hours: " + span1);
Console.WriteLine("12 hours: " + span2);
Console.WriteLine("24 hours: " + span3);
}
}
The output of the above code is −
3 hours: 03:00:00 12 hours: 12:00:00 24 hours: 1.00:00:00
Using TimeSpan.FromHours() with Decimal Values
You can also use fractional hour values to create more precise time spans −
using System;
public class Demo {
public static void Main() {
TimeSpan span1 = TimeSpan.FromHours(1.5); // 1 hour 30 minutes
TimeSpan span2 = TimeSpan.FromHours(2.25); // 2 hours 15 minutes
TimeSpan span3 = TimeSpan.FromHours(0.5); // 30 minutes
Console.WriteLine("1.5 hours: " + span1);
Console.WriteLine("2.25 hours: " + span2);
Console.WriteLine("0.5 hours: " + span3);
Console.WriteLine("Total minutes in 1.5 hours: " + span1.TotalMinutes);
}
}
The output of the above code is −
1.5 hours: 01:30:00 2.25 hours: 02:15:00 0.5 hours: 00:30:00 Total minutes in 1.5 hours: 90
Using TimeSpan.FromHours() with Negative Values
The method also accepts negative values to represent time spans in the past −
using System;
public class Demo {
public static void Main() {
TimeSpan positiveSpan = TimeSpan.FromHours(5);
TimeSpan negativeSpan = TimeSpan.FromHours(-3.5);
Console.WriteLine("Positive 5 hours: " + positiveSpan);
Console.WriteLine("Negative 3.5 hours: " + negativeSpan);
TimeSpan result = positiveSpan + negativeSpan;
Console.WriteLine("Sum of both: " + result);
}
}
The output of the above code is −
Positive 5 hours: 05:00:00 Negative 3.5 hours: -03:30:00 Sum of both: 01:30:00
Conclusion
The TimeSpan.FromHours() method provides a simple and efficient way to create TimeSpan objects from hour values. It accepts both positive and negative decimal values, making it versatile for various time calculation scenarios in C# applications.
