Search code examples
c#humanizer

Humanizer Months, Weeks, Days, Hours


In C# I am using Humanizer and need to know how many Months, Weeks, Days and Hours are in a TimeSpan in a decreasing amount. Basically the duration of the timespan in decreasing units.

For example:

 var z = myTimeSpan.Humanize(???);

 I would like z would be "3 Months, 2 Weeks, 3 Days, 4 Hours"

Solution

  • It doesn't appear to be possible to make Humanizer display months and weeks. Based on the source code that @RufusL linked, this seems to be intentional.

    You could do get months, days, and hours, like so:

    new TimeSpan(109, 4, 0, 0, 0).Humanize(3, maxUnit: TimeUnit.Month)
    // 3 months, 17 days, 4 hours
    

    Or you could do some post-processing with regex (it's kludgey, and doesn't work for other locales, so I can't fully recommend the approach):

    var z = new TimeSpan(109, 4, 0, 0, 0).Humanize(3, maxUnit: TimeUnit.Month);
    z = Regex.Replace(
        z,
        @"(\d+) days?",
        m => TimeSpan.FromDays(int.Parse(m.Groups[1].ToString())).Humanize(2)
    );
    // 3 months, 2 weeks, 3 days, 4 hours