Guest User

Untitled

a guest
Oct 17th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. decimal t = 5.5M;
  2. Console.WriteLine(TimeSpan.FromHours((double)t).ToString());
  3.  
  4. var ts = TimeSpan.FromHours((double)t);
  5. Console.WriteLine("{0} hrs {1} minutes", ts.Hours, ts.Minutes);
  6.  
  7. /// <summary>Converts a decimal e.g. 1.5 to 1 hour 30 minutes</summary>
  8. /// <param name="duration">The time to convert as a double</param>
  9. /// <returns>
  10. /// Returns a string in format:
  11. /// x hours x minutes
  12. /// x hours (if there's no minutes)
  13. /// x minutes (if there's no hours)
  14. /// Will also pluralise the words if required e.g. 1 hour or 3 hours
  15. /// </returns>
  16. public String convertDecimalToHoursMinutes(double time)
  17. {
  18. TimeSpan timespan = TimeSpan.FromHours(time);
  19. int hours = timespan.Hours;
  20. int mins = timespan.Minutes;
  21.  
  22. // Convert to hours and minutes
  23. String hourString = (hours > 0) ? string.Format("{0} " + pluraliseTime(hours, "hour"), hours) : "";
  24. String minString = (mins > 0) ? string.Format("{0} " + pluraliseTime(mins, "minute"), mins) : "";
  25.  
  26. // Add a space between the hours and minutes if necessary
  27. return (hours > 0 && mins > 0) ? hourString + " " + minString : hourString + minString;
  28. }
  29.  
  30. /// <summary>Pluralise hour or minutes based on the amount of time</summary>
  31. /// <param name="num">The number of hours or minutes</param>
  32. /// <param name="word">The word to pluralise e.g. "hour" or "minute"</param>
  33. /// <returns> Returns correct English pluralisation e.g. 3 hours, 1 minute, 0 minutes</returns>
  34. public String pluraliseTime(int num, String word)
  35. {
  36. return (num == 0 || num > 1) ? word + "s" : word;
  37. }
  38.  
  39. var tsExample = TimeSpan.FromHours(timeInDecimal);
  40. var result = $"{tsExample.Hours + (tsExample.Days * 24):00}:{tsExample.Minutes:00}";
Add Comment
Please, Sign In to add comment