Filipe Nóbrega
Filipe Nóbrega

Reputation: 667

How do I convert TimeSpan days into hours format

I have a function that given minutes converts it to a string in the following format hh:mm.

The function works fine, except when the minutes excedes 24 hours. For example, if the input is 1920 minutes the epected output is 32:00 but, is 08:00 (1 day + 8 hours).

The function:

private string NumberToDurationFormat(int number)
{
    TimeSpan timeSpan = TimeSpan.FromMinutes(number);
    return timeSpan.ToString(@"hh\:mm");
}

Upvotes: 0

Views: 894

Answers (1)

Connor Stoop
Connor Stoop

Reputation: 1632

I would do it like this. by doing toString with the 00 it makes sure you have 2 characters.

private string NumberToDurationFormat(int number)
{
    TimeSpan timeSpan = TimeSpan.FromMinutes(number);
    return ((int)timeSpan.TotalHours).ToString("00") + ":" + timeSpan.Minutes.ToString("00");
}

Upvotes: 2

Related Questions