Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities.
You can install Humanizer as a nuget package:
English only: Humanizer.Core
All languages: Humanizer
The following frameworks are supported: net4.8, net6, net7, and net8
Note: The nuget also targets netstandard2. This is to enable scenario where netstandard2 is required. For example Roslyn Analyzers or MSBuil tasks. Other frameworks (other than listed above) that can consume netstandard2 (example net4.6.1 through to net 4.7.2) are not supported. For example net4.6.1 through to net4.7.2 are not supported.
Also Humanizer symbols are source indexed with SourceLink and are included in the package so you can step through Humanizer code while debugging your code.
You choose which packages based on what NuGet package(s) you install. By default, the main Humanizer 2.0 package installs all supported languages exactly like it does in 1.x. If you're not sure, then just use the main Humanizer package.
Here are the options:
Humanizer package. This pulls in Humanizer.Core and all language packages.Humanizer.Core package. Only the English language resources will be availableHumanizer.Core.fr. You can include multiple languages by installing however many language packages you want.The detailed explanation for how this works is in the comments here.
Humanize string extensions allow you turn an otherwise computerized string into a more readable human-friendly one.
The foundation of this was set in the BDDfy framework where class names, method names and properties are turned into human readable sentences.
"PascalCaseInputStringIsTurnedIntoSentence".Humanize() => "Pascal case input string is turned into sentence" "Underscored_input_string_is_turned_into_sentence".Humanize() => "Underscored input string is turned into sentence" "Underscored_input_String_is_turned_INTO_sentence".Humanize() => "Underscored input String is turned INTO sentence"
Note that a string that contains only upper case letters, and consists only of one word, is always treated as an acronym (regardless of its length). To guarantee that any arbitrary string will always be humanized you must use a transform (see Transform method below):
// acronyms are left intact "HTML".Humanize() => "HTML" // any unbroken upper case string is treated as an acronym "HUMANIZER".Humanize() => "HUMANIZER" "HUMANIZER".Transform(To.LowerCase, To.TitleCase) => "Humanizer"
You may also specify the desired letter casing:
"CanReturnTitleCase".Humanize(LetterCasing.Title) => "Can Return Title Case" "Can_return_title_Case".Humanize(LetterCasing.Title) => "Can Return Title Case" "CanReturnLowerCase".Humanize(LetterCasing.LowerCase) => "can return lower case" "CanHumanizeIntoUpperCase".Humanize(LetterCasing.AllCaps) => "CAN HUMANIZE INTO UPPER CASE"
The
LetterCasingAPI and the methods accepting it are legacy from V0.2 era and will be deprecated in the future. Instead of that, you can useTransformmethod explained below.
Much like you can humanize a computer friendly into human friendly string you can dehumanize a human friendly string into a computer friendly one:
"Pascal case input string is turned into sentence".Dehumanize() => "PascalCaseInputStringIsTurnedIntoSentence"
There is a Transform method that supersedes LetterCasing, ApplyCase and Humanize overloads that accept LetterCasing.
Transform method signature is as follows:
string Transform(this string input, params IStringTransformer[] transformers)
And there are some out of the box implementations of IStringTransformer for letter casing:
"Sentence casing".Transform(To.LowerCase) => "sentence casing" "Sentence casing".Transform(To.SentenceCase) => "Sentence casing" "Sentence casing".Transform(To.TitleCase) => "Sentence Casing" "Sentence casing".Transform(To.UpperCase) => "SENTENCE CASING"
LowerCase is a public static property on To class that returns an instance of private ToLowerCase class that implements IStringTransformer and knows how to turn a string into lower case.
The benefit of using Transform and IStringTransformer over ApplyCase and LetterCasing is that LetterCasing is an enum and you're limited to use what's in the framework
while IStringTransformer is an interface you can implement in your codebase once and use it with Transform method allowing for easy extension.
You can truncate a string using the Truncate method:
"Long text to truncate".Truncate(10) => "Long text…"
By default the '…' character is used to truncate strings. The advantage of using the '…' character instead of "..." is that the former only takes a single character and thus allows more text to be shown before truncation. If you want, you can also provide your own truncation string:
"Long text to truncate".Truncate(10, "---") => "Long te---"
The default truncation strategy, Truncator.FixedLength, is to truncate the input string to a specific length, including the truncation string length.
There are two more truncator strategies available: one for a fixed number of (alpha-numerical) characters and one for a fixed number of words.
To use a specific truncator when truncating, the two Truncate methods shown in the previous examples all have an overload that allow you to specify the ITruncator instance to use for the truncation.
Here are examples on how to use the three provided truncators:
"Long text to truncate".Truncate(10, Truncator.FixedLength) => "Long text…" "Long text to truncate".Truncate(10, "---", Truncator.FixedLength) => "Long te---" "Long text to truncate".Truncate(6, Truncator.FixedNumberOfCharacters) => "Long t…" "Long text to truncate".Truncate(6, "---", Truncator.FixedNumberOfCharacters) => "Lon---" "Long text to truncate".Truncate(2, Truncator.FixedNumberOfWords) => "Long text…" "Long text to truncate".Truncate(2, "---", Truncator.FixedNumberOfWords) => "Long text---"
Note that you can also use create your own truncator by implementing the ITruncator interface.
There is also an option to choose whether to truncate the string from the beginning (TruncateFrom.Left) or the end (TruncateFrom.Right).
Default is the right as shown in the examples above. The examples below show how to truncate from the beginning of the string:
"Long text to truncate".Truncate(10, Truncator.FixedLength, TruncateFrom.Left) => "… truncate" "Long text to truncate".Truncate(10, "---", Truncator.FixedLength, TruncateFrom.Left) => "---runcate" "Long text to truncate".Truncate(10, Truncator.FixedNumberOfCharacters, TruncateFrom.Left) => "…o truncate" "Long text to truncate".Truncate(16, "---", Truncator.FixedNumberOfCharacters, TruncateFrom.Left) => "---ext to truncate" "Long text to truncate".Truncate(2, Truncator.FixedNumberOfWords, TruncateFrom.Left) => "…to truncate" "Long text to truncate".Truncate(2, "---", Truncator.FixedNumberOfWords, TruncateFrom.Left) => "---to truncate"
Calling ToString directly on enum members usually results in less than ideal output for users. The solution to this is usually to use DescriptionAttribute data annotation and then read that at runtime to get a more friendly output. That is a great solution; but more often than not we only need to put some space between words of an enum member - which is what String.Humanize() does well. For an enum like:
public enum EnumUnderTest { [Description("Custom description")] MemberWithDescriptionAttribute, MemberWithoutDescriptionAttribute, ALLCAPITALS }
You will get:
// DescriptionAttribute is honored EnumUnderTest.MemberWithDescriptionAttribute.Humanize() => "Custom description" // In the absence of Description attribute string.Humanizer kicks in EnumUnderTest.MemberWithoutDescriptionAttribute.Humanize() => "Member without description attribute" // Of course you can still apply letter casing EnumUnderTest.MemberWithoutDescriptionAttribute.Humanize().Transform(To.TitleCase) => "Member Without Description Attribute"
You are not limited to DescriptionAttribute for custom description. Any attribute applied on enum members with a string Description property counts.
This is to help with platforms with missing DescriptionAttribute and also for allowing subclasses of the DescriptionAttribute.
You can even configure the name of the property of attibute to use as description.
Configurator.EnumDescriptionPropertyLocator = p => p.Name == "Info"
If you need to provide localised descriptions you can use DisplayAttribute data annotation instead.
public enum EnumUnderTest { [Display(Description = "EnumUnderTest_Member", ResourceType = typeof(Project.Resources))] Member }
You will get:
EnumUnderTest.Member.Humanize() => "content" // from Project.Resources found under "EnumUnderTest_Member" resource key
Hopefully this will help avoid littering enums with unnecessary attributes!
Dehumanizes a string into the Enum it was originally Humanized from! The API looks like:
public static TTargetEnum DehumanizeTo<TTargetEnum>(this string input)
And the usage is:
"Member without description attribute".DehumanizeTo<EnumUnderTest>() => EnumUnderTest.MemberWithoutDescriptionAttribute
And just like the Humanize API it honors the Description attribute. You don't have to provide the casing you provided during humanization: it figures it out.
There is also a non-generic counterpart for when the original Enum is not known at compile time:
public static Enum DehumanizeTo(this string input, Type targetEnum, NoMatch onNoMatch = NoMatch.ThrowsException)
which can be used like:
"Member without description attribute".DehumanizeTo(typeof(EnumUnderTest)) => EnumUnderTest.MemberWithoutDescriptionAttribute
By default both methods throw a NoMatchFoundException when they cannot match the provided input against the target enum.
In the non-generic method you can also ask the method to return null by setting the second optional parameter to NoMatch.ReturnsNull.
You can Humanize an instance of DateTime or DateTimeOffset and get back a string telling how far back or forward in time that is:
DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday" DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago" DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow" DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now" DateTimeOffset.UtcNow.AddHours(1).Humanize() => "an hour from now"
Humanizer supports both local and UTC dates as well as dates with offset (DateTimeOffset). You could also provide the date you want the input date to be compared against. If null, it will use the current date as comparison base.
Also, culture to use can be specified explicitly. If it is not, current thread's current UI culture is used.
Here is the API signature:
public static string Humanize(this DateTime input, bool utcDate = true, DateTime? dateToCompareAgainst = null, CultureInfo culture = null) public static string Humanize(this DateTimeOffset input, DateTimeOffset? dateToCompareAgainst = null, CultureInfo culture = null)
Many localizations are available for this method. Here is a few examples:
// In ar culture DateTime.UtcNow.AddDays(-1).Humanize() => "أمس" DateTime.UtcNow.AddDays(-2).Humanize() => "منذ يومين" DateTime.UtcNow.AddDays(-3).Humanize() => "منذ 3 أيام" DateTime.UtcNow.AddDays(-11).Humanize() => "منذ 11 يوم" // In ru-RU culture DateTime.UtcNow.AddMinutes(-1).Humanize() => "минуту назад" DateTime.UtcNow.AddMinutes(-2).Humanize() => "2 минуты назад" DateTime.UtcNow.AddMinutes(-10).Humanize() => "10 минут назад" DateTime.UtcNow.AddMinutes(-21).Humanize() => "21 минуту назад" DateTime.UtcNow.AddMinutes(-22).Humanize() => "22 минуты назад" DateTime.UtcNow.AddMinutes(-40).Humanize() => "40 минут назад"
There are two strategies for DateTime.Humanize: the default one as seen above and a precision based one.
To use the precision based strategy you need to configure it:
Configurator.DateTimeHumanizeStrategy = new PrecisionDateTimeHumanizeStrategy(precision: .75); Configurator.DateTimeOffsetHumanizeStrategy = new PrecisionDateTimeOffsetHumanizeStrategy(precision: .75); // configure when humanizing DateTimeOffset
The default precision is set to .75 but you can pass your desired precision too. With precision set to 0.75:
44 seconds => 44 seconds ago/from now 45 seconds => one minute ago/from now 104 seconds => one minute ago/from now 105 seconds => two minutes ago/from now 25 days => a month ago/from now
No dehumanization for dates as Humanize is a lossy transformation and the human friendly date is not reversible
You can call Humanize on a TimeSpan to a get human friendly representation for it:
TimeSpan.FromMilliseconds(1).Humanize() => "1 millisecond" TimeSpan.FromMilliseconds(2).Humanize() => "2 milliseconds" TimeSpan.FromDays(1).Humanize() => "1 day" TimeSpan.FromDays(16).Humanize() => "2 weeks"
There is an optional precision parameter for TimeSpan.Humanize which allows you to specify the precision of the returned value.
The default value of precision is 1 which means only the largest time unit is returned like you saw in TimeSpan.FromDays(16).Humanize().
Here is a few examples of specifying precision:
TimeSpan.FromDays(1).Humanize(precision:2) => "1 day" // no difference when there is only one unit in the provided TimeSpan TimeSpan.FromDays(16).Humanize(2) => "2 weeks, 2 days" // the same TimeSpan value with different precision returns different results TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks" TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour" TimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds" TimeSpan.FromMilliseconds(1299630020).Humanize(5) => "2 weeks, 1 day, 1 hour, 30 seconds, 20 milliseconds"
By default when using precision parameter empty time units are not counted towards the precision of the returned value.
If this behavior isn't desired for you, you can use the overloaded TimeSpan.Humanize method with countEmptyUnits parameter. Leading empty time units never count.
Here is an example showing the difference of counting empty units:
TimeSpan.FromMilliseconds(3603001).Humanize(3) => "1 hour, 3 seconds, 1 millisecond" TimeSpan.FromMilliseconds(3603001).Humanize(3, countEmptyUnits:true) => "1 hour, 3 seconds"
Many localizations are available for this method:
// in de-DE culture TimeSpan.FromDays(1).Humanize() => "Ein Tag" TimeSpan.FromDays(2).Humanize() => "2 Tage" // in sk-SK culture TimeSpan.FromMilliseconds(1).Humanize() => "1 milisekunda" TimeSpan.FromMilliseconds(2).Humanize() => "2 milisekundy" TimeSpan.FromMilliseconds(5).Humanize() => "5 milisekúnd"
Culture to use can be specified explicitly. If it is not, current thread's current UI culture is used. Example:
TimeSpan.FromDays(1).Humanize(culture: "ru-RU") => "один день"
In addition, a minimum unit of time may be specified to avoid rolling down to a smaller unit. For example:
TimeSpan.FromMilliseconds(122500).Humanize(minUnit: TimeUnit.Second) => "2 minutes, 2 seconds" // instead of 2 minutes, 2 seconds, 500 milliseconds TimeSpan.FromHours(25).Humanize(minUnit: TimeUnit.Day) => "1 Day" //instead of 1 Day, 1 Hour
In addition, a maximum unit of time may be specified to avoid rolling up to the next largest unit. For example:
TimeSpan.FromDays(7).Humanize(maxUnit:


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频


实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。


选题、配图、 成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。


像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考 、自主完成、并且交付结果的AI智能体。


AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。


一站式AI创作平台
提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号