Isn't there a TimeSpan.Duration
method? I think this would handle what you are trying to do.
Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object.
static string ToHMString(TimeSpan timespan) {
if (timespan.Ticks < 0) return "-" + ToHMString(timespan.Negate());
return timespan.TotalHours.ToString("#0") + ":" + timespan.Minutes.ToString("00");
}
Console.WriteLine(ToHMString(TimeSpan.FromHours(3))); //Prints "3:00"
Console.WriteLine(ToHMString(TimeSpan.FromHours(-27.75))); //Prints "-28:45"
This will also work correctly if the timespan is longer than 24 hours.
Just multiply it by -1 or use an absolute value function.
There is a Negate method in the TimeSpan class.
Link to the MSDN documentation: TimeSpan.Negate Method()
The simple solution would be to do:
string format = "HH:mm";
if(hours < 0)
format = "-" + format;
hours = Math.Abs(hours)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With