/// <summary> /// Converts this timespan to a human readable string. /// </summary> /// <param name="timespan">The timespan.</param> /// <param name="parts">The parts (flagable).</param> /// <returns> /// Always returns a value (empty when no ticks) to allow method chaining. /// </returns> public static string Humanise(this TimeSpan timespan, TimeSpanPart parts = TimeSpanPart.Day | TimeSpanPart.Hour | TimeSpanPart.Minute | TimeSpanPart.Second) { var result = string.Empty; if (timespan.Ticks != 0) { var formattedSections = new List <string>(); if (parts.HasFlag(TimeSpanPart.Day)) { formattedSections.Add(FormatSection(timespan.Days, TimeSpanPart.Day)); } if (parts.HasFlag(TimeSpanPart.Hour)) { formattedSections.Add(FormatSection(timespan.Hours, TimeSpanPart.Hour)); } if (parts.HasFlag(TimeSpanPart.Minute)) { formattedSections.Add(FormatSection(timespan.Minutes, TimeSpanPart.Minute)); } if (parts.HasFlag(TimeSpanPart.Second)) { formattedSections.Add(FormatSection(timespan.Seconds, TimeSpanPart.Second)); } result = string.Join(", ", formattedSections.Where(s => !string.IsNullOrEmpty(s))); if (string.IsNullOrEmpty(result)) { if (parts.HasFlag(TimeSpanPart.Second)) { result = "Less than a second"; } else if (parts.HasFlag(TimeSpanPart.Minute)) { result = "Less than a minute"; } else if (parts.HasFlag(TimeSpanPart.Hour)) { result = "Less than an hour"; } else if (parts.HasFlag(TimeSpanPart.Day)) { result = "Less than a day"; } } } return(result); }
/// <summary> /// Converts this timespan to a human readable string. /// </summary> /// <param name="timespan">The timespan.</param> /// <param name="parts">The parts (flagable).</param> /// <returns> /// Always returns a value (empty when no ticks) to allow method chaining. /// </returns> public static string Humanise(this TimeSpan timespan, TimeSpanPart parts = TimeSpanPart.Day | TimeSpanPart.Hour | TimeSpanPart.Minute | TimeSpanPart.Second) { var result = string.Empty; if (timespan.Ticks > 0) { var formattedSections = new List<string>(); if (parts.HasFlag(TimeSpanPart.Day)) { formattedSections.Add(FormatSection(timespan.Days, TimeSpanPart.Day)); } if (parts.HasFlag(TimeSpanPart.Hour)) { formattedSections.Add(FormatSection(timespan.Hours, TimeSpanPart.Hour)); } if (parts.HasFlag(TimeSpanPart.Minute)) { formattedSections.Add(FormatSection(timespan.Minutes, TimeSpanPart.Minute)); } if (parts.HasFlag(TimeSpanPart.Second)) { formattedSections.Add(FormatSection(timespan.Seconds, TimeSpanPart.Second)); } result = string.Join(", ", formattedSections.Where(s => !string.IsNullOrEmpty(s))); if (string.IsNullOrEmpty(result)) { if (parts.HasFlag(TimeSpanPart.Second)) { result = "Less than a second"; } else if (parts.HasFlag(TimeSpanPart.Minute)) { result = "Less than a minute"; } else if (parts.HasFlag(TimeSpanPart.Hour)) { result = "Less than an hour"; } else if (parts.HasFlag(TimeSpanPart.Day)) { result = "Less than a day"; } } } return result; }