1

I have the following code. Apologise if some of it is redundant. I'm a novice using an older version of the .NET framework that forbids top-level statements.

using System;

namespace Whatever
{
    public class DoesNotMatter
    {
       public static string MinsToHoursAndMins(int Mins)
       {
              var SensibleTimes = TimeSpan.FromMinutes(Mins);
              return $"{(int) SensibleTimes.TotalHours}.{SensibleTimes:mm}"
       }
    }
}

If it weren't for the call to .TotalHours, I could make this a one-liner such as $"{TimeSpan.FromMinutes(Mins):mm}". Is there any way to do the same with .TotalHours included, even on the newest C#/.NET versions? In other words, how can I avoid declaring the SensibleTimes varible?

J. Mini
  • 1,868
  • 1
  • 9
  • 38
  • 1
    There's no format string for "Total whole hours". Short of going down the `ICustomFormatter` route... You could always skip `TimeSpan` and just do `$"{mins / 60}.{mins % 60}"` of course... – canton7 Nov 28 '22 at 12:58
  • 2
    Write an Extension method for TimeSpan returning the format of your liking and use that in the interpolated string. – Ralf Nov 28 '22 at 13:04
  • Top level statements were introduced in C# 10 and are not dependent on the Framework version. You can include `latest` in your project file to use the latest C# version. see: [C# language versioning / Override a default](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version#override-a-default). But in this case it would be enough to only include the method, because the class declaration adds no relevant information. – Olivier Jacot-Descombes Nov 28 '22 at 13:06
  • @canton7 I wouldn't be surprised if what you've said is the full truth. Expand on that, e.g. with a documentation link showing that there's no such formatter or an implementation of the `ICustomerFormatter`, and you've probably got the best answer that we're going to get. – J. Mini Nov 28 '22 at 13:40
  • Does this answer your question? [How can I String.Format a TimeSpan object with a custom format in .NET?](https://stackoverflow.com/questions/574881/how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net) – Orace Nov 28 '22 at 13:41
  • @Orace It helps, but it missed the fact that `.TotalHours` has no custom format strings. – J. Mini Nov 28 '22 at 13:42
  • You are right, custom format is a dead end. As canton7 said, `ICustomFormatter` is to messy. And as mentioned by Ralf, the best solution for a _one-liner_ is probably an extension method. Like the one provided by [Humanizer](https://github.com/Humanizr/Humanizer#humanize-timespan) – Orace Nov 28 '22 at 13:49

1 Answers1

0
return (Mins / 60).ToString("00")+"."+ (Mins % 60).ToString("00");
Hossein Sabziani
  • 1
  • 2
  • 15
  • 20