I am writing this question as I am asking for the best way to do this. I have many of these in my program and I want to make a method to convert a Int32 which contains a seconds of a timer into a nicely formatted string.
So for example, if my timer int was at lets say a random number like 16429 it would be:
4 hours, 32 minutes and 9 seconds
If it was 600, it would be:
10 minutes
If it was 60, it would be
1 minute
If it was 172801, it would be
2 days and 1 second
If it was 32, it would be
32 seconds
I want the "s" 's at the end of each word like "minute", "second" and "day" to only put S if it isn't equal to 1, therefor it isn't really needed to be pronounced correctly. I also only want days and hours and other things added if they are needed, so if the timer is below 1 day in seconds, it only shows hours, minutes and seconds, or what is needed.
What is the best way to achieve something like this? I have this function below, but it is very messy and only goes up to minutes and seconds, not hours or days:
public static string GetConvertedTime(int timer)
{
int Minutes = timer / 60;
int Seconds = timer - Minutes * 60;
if (timer < 60)
{
string secs = (Seconds != 1) ? "s" : "";
return "" + timer + " second" + secs;
}
else
{
if (Seconds < 1)
{
string mins = (Minutes != 1) ? "s" : "";
return "" + Minutes + " minute" + mins;
}
else
{
string mins = (Minutes != 1) ? "s" : "";
string secs = (Seconds != 1) ? "s" : "";
return "" + Minutes + " minute" + mins + " and " + Seconds + " second" + secs;
}
}
}
What exactly is the best way to do this?
You can try this library named Humanizer
Probably the best way I can think of is to use a
TimeSpan
like so:if you need to hide the empty leading values:
"Best way" is awfully subjective. DRY is usually best, considering localization and non-regular pluralization forms is usually best, keeping it short and snappy is usually best: