Skip to content

Instantly share code, notes, and snippets.

@diademoff
Created July 22, 2021 18:11
Show Gist options
  • Save diademoff/d302f1c5a4df8ea93eda42074228c790 to your computer and use it in GitHub Desktop.
Save diademoff/d302f1c5a4df8ea93eda42074228c790 to your computer and use it in GitHub Desktop.
Convert seconds to human readable format
using System.Collections.Generic;
using System.Linq;
public class HumanTimeFormat
{
protected class DateComponent
{
// One unit of current component
public int InSeconds { get; }
// String present of current component
public string Unit { get; }
public string UnitPlural => Unit + 's';
public DateComponent(string unit, int inSeconds)
{
this.Unit = unit;
this.InSeconds = inSeconds;
}
public string Format(int seconds)
{
if (seconds < InSeconds)
return "";
seconds -= seconds % InSeconds;
int value = seconds / InSeconds;
return value == 1 ? $"{value} {Unit}" : $"{value} {UnitPlural}";
}
// Number of seconds left after converting to current unit
public int SecondsLeft(int seconds) => seconds % InSeconds;
}
static DateComponent[] components;
static HumanTimeFormat()
{
components = new DateComponent[]
{
new DateComponent("year", 365 * 24 * 60 * 60),
new DateComponent("day", 24 * 60 * 60),
new DateComponent("hour", 60 * 60),
new DateComponent("minute", 60),
new DateComponent("second", 1)
};
}
public static string FormatSeconds(int seconds)
{
if (seconds == 0)
return "now";
List<string> dateComponents = new List<string>();
for (int i = 0; i < components.Length; i++)
{
dateComponents.Add(components[i].Format(seconds));
seconds = components[i].SecondsLeft(seconds);
}
dateComponents = dateComponents.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
if (dateComponents.Count == 1)
return dateComponents[0];
var last = dateComponents.Last();
dateComponents.RemoveAt(dateComponents.Count - 1);
return string.Join(", ", dateComponents) + $" and {last}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment