user9001
user9001

Reputation: 13

Timespan.FromHours for decimal conversion

I am using TimeSpan.FromHours(9.30) which gives "09:18:00" and If I use TimeSpan.Parse("09:30") then it will return 09:30. Both are same but TimeSpan.FromHours is a lot safer and more efficient.

Please advice why result is different?

Thanks,

Upvotes: 1

Views: 573

Answers (1)

Fildor
Fildor

Reputation: 16158

FromHours is not of the format "h.mm", it is fractions of hours.

So you want TimeSpan.FromHours(9.5) (Think "9 hours and a half")

See also: TimeSpan.FromHours(Double)

Mind: While FromHours takes a Double, it will only be accurate to the nearest Millisecond

TimeSpan.Parse(String) takes a time interval (heads up: dependend on system culture *) ), so here you have for example "09:30" as actually 9 hours, 30 minutes.

*) "dependend on system culture" means: "5.123" would be 5 seconds, 123 millis in US Culture, but would throw an exception in cultures that use "," as decimal separator. For details see linked docs.

Upvotes: 1

Related Questions