How to display shortened versions of time units #1568
-
|
I'd like to show "ms" instead of "milliseconds" on Is this possible? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Hello! Currently, Humanizer is designed for natural language prose (e.g., '2 minutes, 400 milliseconds') rather than technical abbreviations. There isn't a built-in parameter for 'ms'. However, a clean way to handle this in your project is to create a small extension method that maps the full units to their abbreviations. This keeps the 'humanized' logic while giving you the short format you need: using Humanizer;
using System.Text.RegularExpressions;
public static class HumanizerExtensions
{
private static readonly Dictionary<string, string> Abbreviations = new()
{
{ "millisecond", "ms" },
{ "second", "s" },
{ "minute", "min" },
{ "hour", "h" },
{ "day", "d" }
};
public static string HumanizeShort(this TimeSpan timeSpan, int precision = 1)
{
string humanized = timeSpan.Humanize(precision);
foreach (var pair in Abbreviations)
{
// Matches the word, its plural, and handles word boundaries
humanized = Regex.Replace(humanized, $@"\b{pair.Key}s?\b", pair.Value);
}
return humanized;
}
}
// Usage:
// TimeSpan.FromMilliseconds(400).HumanizeShort(); // "400 ms"
// TimeSpan.FromSeconds(62).HumanizeShort(2); // "1 min, 2 s"There are some performance optimizations you can make if you want, but hope this helps! 😄 |
Beta Was this translation helpful? Give feedback.
Hello!
Currently, Humanizer is designed for natural language prose (e.g., '2 minutes, 400 milliseconds') rather than technical abbreviations. There isn't a built-in parameter for 'ms'.
However, a clean way to handle this in your project is to create a small extension method that maps the full units to their abbreviations. This keeps the 'humanized' logic while giving you the short format you need: