.NET HELP

Humanizer C# (How It Works For Developers)

Published July 1, 2024
Share:

Humanizer is a powerful and flexible .NET library that simplifies and humanizes the process of working with data, especially when it comes to displaying information in a user-friendly format. Whether you need to convert dates to relative time strings ("3 days ago"), pluralize words, format numbers as words, or work with enums, displaying strings, Pascal case input strings as sentences with custom descriptions, underscored input strings to normal title case strings, and long text truncation, Humanizer provides a plethora of tools and extension methods to handle these tasks elegantly in C#.NET to convert dehumanized input strings into sentences.

In this article, we will discuss a detailed tutorial of Humanizer in C#. We will also discuss how to generate PDF documents using Humanizer and IronPDF for C# PDF Library.

Setting Up Humanizer in C#

To get started with Humanizer, you need to install the library via NuGet. In your project, you can do this through the Package Manager Console with the following command:

Install-Package Humanizer
Install-Package Humanizer
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package Humanizer
VB   C#

Alternatively, if you are using the .NET Core CLI, you can add Humanizer with:

dotnet add package Humanizer

After installation, you can start using Humanizer by including the appropriate namespace in your C# files:

using Humanizer;
using Humanizer;
Imports Humanizer
VB   C#

Humanizing Dates and Times

One of the most common uses of Humanizer is to convert dates and times into human-readable formats, timespans, numbers, and quantities using the Humanize method. This is particularly useful for displaying relative times, such as "2 hours ago" or "in 5 days".

Example: Humanizing Relative Time

DateTime pastDate = DateTime.Now.AddDays(-3);
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"
DateTime pastDate = DateTime.Now.AddDays(-3);
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"
Dim pastDate As DateTime = DateTime.Now.AddDays(-3)
Dim humanizedTime As String = pastDate.Humanize() ' Output: "3 days ago"
Dim futureDate As DateTime = DateTime.Now.AddHours(5)
Dim futureHumanizedTime As String = futureDate.Humanize() ' Output: "in 5 hours"
VB   C#

The Humanizer extension method automatically handles different time units and even adjusts for grammatical correctness.

Humanizer C# (How It Works For Developers): Figure 1 - Humanizing Relative Time Output

Humanizing TimeSpans

Humanizer can also humanize TimeSpan objects, making it easy to display durations in a readable format.

Example: Humanizing TimeSpan

TimeSpan timeSpan = TimeSpan.FromMinutes(123);
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
TimeSpan timeSpan = TimeSpan.FromMinutes(123);
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
Dim timeSpan As TimeSpan = System.TimeSpan.FromMinutes(123)
Dim humanizedTimeSpan As String = timeSpan.Humanize(2) ' Output: "2 hours, 3 minutes"
VB   C#

Humanizer C# (How It Works For Developers): Figure 2 - Humanizing TimeSpan Output

Working with Numbers

Humanizer provides several methods to convert numbers into human-readable words and to handle ordinal numbers.

Example: Converting Numbers to Words

int number = 123;
string words = number.ToWords(); // Output: "one hundred and twenty-three"
int number = 123;
string words = number.ToWords(); // Output: "one hundred and twenty-three"
Dim number As Integer = 123
Dim words As String = number.ToWords() ' Output: "one hundred and twenty-three"
VB   C#

Humanizer C# (How It Works For Developers): Figure 3 - Number to Word Output

Example: Converting Numbers to Ordinals

int number = 21;
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
int number = 21;
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
Dim number As Integer = 21
Dim ordinal As String = number.ToOrdinalWords() ' Output: "twenty-first"
VB   C#

Humanizer C# (How It Works For Developers): Figure 4 - Number to Ordinal Output

Pluralization and Singularization

Humanizer makes it easy to convert words between their singular and plural forms, which is useful for dynamically generating long text based on quantity.

Example: Pluralizing and Singularizing Words

string singular = "car";
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
string singularForm = word.Singularize(); // Output: "person"
string singular = "car";
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
string singularForm = word.Singularize(); // Output: "person"
Dim singular As String = "car"
Dim plural As String = singular.Pluralize() ' Output: "cars"
Dim word As String = "people"
Dim singularForm As String = word.Singularize() ' Output: "person"
VB   C#

Humanizer handles irregular pluralizations and singularizations as well, making it robust for various use cases.

Humanizer C# (How It Works For Developers): Figure 5 - Pluralize and Singularize Output

Formatting Enums

Enums are frequently used in C# applications to represent a set of named constants. Humanizer can convert enum values to human-readable strings.

Example: Humanizing Enums

MyEnum enumValue = MyEnum.FirstValue;
string humanizedEnum = enumValue.Humanize();
System.Console.WriteLine(humanizedEnum);
public enum MyEnum
{
    FirstValue,
    SecondValue
} // Output: "First value"
MyEnum enumValue = MyEnum.FirstValue;
string humanizedEnum = enumValue.Humanize();
System.Console.WriteLine(humanizedEnum);
public enum MyEnum
{
    FirstValue,
    SecondValue
} // Output: "First value"
Private enumValue As MyEnum = MyEnum.FirstValue
Private humanizedEnum As String = enumValue.Humanize()
System.Console.WriteLine(humanizedEnum)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'public enum MyEnum
'{
'	FirstValue,
'	SecondValue
'} ' Output: "First value"
VB   C#

This method can be particularly useful for displaying user-friendly labels in UIs.

Humanizer C# (How It Works For Developers): Figure 6 - Humanize Enum Output

Humanizing Byte Sizes

Another handy feature of Humanizer is the ability to humanize byte sizes, converting large byte values into readable formats like KB, MB, or GB.

Example: Humanizing Byte Sizes

long bytes = 1048576;
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"
long bytes = 1048576;
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"
Dim bytes As Long = 1048576
Dim humanizedBytes As String = bytes.Bytes().Humanize() ' Output: "1 MB"
VB   C#

Humanizer C# (How It Works For Developers): Figure 7 - Humanizing Byte Size Output

Advanced Scenarios

Humanizer is not limited to the basic scenarios described above. It supports a wide range of advanced features such as the Truncate method and multiple languages and extensions.

Example: Humanizing DateTime Offsets

Humanizer can also handle DateTimeOffset, which is useful for applications dealing with time zones.

DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"
DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"
Dim dateTimeOffset As DateTimeOffset = System.DateTimeOffset.Now.AddDays(-2)
Dim humanizedDateTimeOffset As String = dateTimeOffset.Humanize() ' Output: "2 days ago"
VB   C#

Humanizer C# (How It Works For Developers): Figure 8 - Humanizing DateTime Offset Output

Performance Considerations

Humanizer is designed to be efficient, but like any library, its performance depends on how it is used. For applications requiring high performance, especially those dealing with large datasets or real-time processing, it is essential to consider the impact of frequent humanization operations.

IronPDF for C

IronPDF is a comprehensive PDF generation and manipulation library for .NET applications. It enables developers to create, read, edit, and extract content from PDF files with ease. IronPDF is designed to be user-friendly, offering a wide range of functionalities including converting HTML to PDF, merging documents, adding watermarks, and much more. Its versatility and powerful features make it an excellent choice for handling PDF documents in C# projects.

Installing IronPDF via NuGet Package Manager

Follow these steps to install IronPDF using the NuGet Package Manager:

  1. Open Your Project in Visual Studio:

    • Launch Visual Studio and open your existing C# project or create a new one.
  2. Open the NuGet Package Manager:

    • Right-click on your project in the Solution Explorer.
    • Select "Manage NuGet Packages…" from the context menu.

Humanizer C# (How It Works For Developers): Figure 9 - NuGet Package Manager

  1. Install IronPDF:

    • In the NuGet Package Manager, go to the "Browse" tab.
    • Search for IronPDF.
    • Select the IronPDF package from the search results.
    • Click the "Install" button to add IronPDF to your project.

Humanizer C# (How It Works For Developers): Figure 10 - IronPDF

By following these steps, IronPDF will be installed and ready to use in your C# project, allowing you to leverage its powerful PDF manipulation capabilities.

C# Humanizer and IronPDF Code Example

using Humanizer;
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Instantiate Renderer
        var renderer = new ChromePdfRenderer();
        List<string> content = GenerateHumanizedContent();
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Iterate over each item in the List and add it to the HTML string
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Export to a file or stream
        pdf.SaveAs("output.pdf");
    }

    static List<string> GenerateHumanizedContent()
    {
        List<string> content = new List<string>();

        // DateTime examples
        DateTime pastDate = DateTime.Now.AddDays(-3);
        DateTime futureDate = DateTime.Now.AddHours(5);
        content.Add($"DateTime.Now: {DateTime.Now}");
        content.Add($"3 days ago: {pastDate.Humanize()}");
        content.Add($"In 5 hours: {futureDate.Humanize()}");

        // TimeSpan examples
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}");

        // Number examples
        int number = 12345;
        content.Add($"Number 12345 in words: {number.ToWords()}");
        content.Add($"Ordinal of 21: {21.ToOrdinalWords()}");

        // Pluralization examples
        string singular = "car";
        content.Add($"Plural of 'car': {singular.Pluralize()}");
        string plural = "children";
        content.Add($"Singular of 'children': {plural.Singularize()}");

        // Byte size examples
        long bytes = 1048576;
        content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}");

        return content;
    }
}
using Humanizer;
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Instantiate Renderer
        var renderer = new ChromePdfRenderer();
        List<string> content = GenerateHumanizedContent();
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Iterate over each item in the List and add it to the HTML string
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Export to a file or stream
        pdf.SaveAs("output.pdf");
    }

    static List<string> GenerateHumanizedContent()
    {
        List<string> content = new List<string>();

        // DateTime examples
        DateTime pastDate = DateTime.Now.AddDays(-3);
        DateTime futureDate = DateTime.Now.AddHours(5);
        content.Add($"DateTime.Now: {DateTime.Now}");
        content.Add($"3 days ago: {pastDate.Humanize()}");
        content.Add($"In 5 hours: {futureDate.Humanize()}");

        // TimeSpan examples
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}");

        // Number examples
        int number = 12345;
        content.Add($"Number 12345 in words: {number.ToWords()}");
        content.Add($"Ordinal of 21: {21.ToOrdinalWords()}");

        // Pluralization examples
        string singular = "car";
        content.Add($"Plural of 'car': {singular.Pluralize()}");
        string plural = "children";
        content.Add($"Singular of 'children': {plural.Singularize()}");

        // Byte size examples
        long bytes = 1048576;
        content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}");

        return content;
    }
}
Imports Humanizer
Imports IronPdf
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		' Instantiate Renderer
		Dim renderer = New ChromePdfRenderer()
		Dim content As List(Of String) = GenerateHumanizedContent()
		Dim htmlContent As String = "<h1>Humanizer Examples</h1><ul>"

		' Iterate over each item in the List and add it to the HTML string
		For Each item In content
			htmlContent &= $"<li>{item}</li>"
		Next item
		htmlContent &= "</ul>"

		' Create a PDF from an HTML string using C#
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

		' Export to a file or stream
		pdf.SaveAs("output.pdf")
	End Sub

	Private Shared Function GenerateHumanizedContent() As List(Of String)
		Dim content As New List(Of String)()

		' DateTime examples
		Dim pastDate As DateTime = DateTime.Now.AddDays(-3)
		Dim futureDate As DateTime = DateTime.Now.AddHours(5)
		content.Add($"DateTime.Now: {DateTime.Now}")
		content.Add($"3 days ago: {pastDate.Humanize()}")
		content.Add($"In 5 hours: {futureDate.Humanize()}")

		' TimeSpan examples
		Dim timeSpan As TimeSpan = System.TimeSpan.FromMinutes(123)
		content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}")

		' Number examples
		Dim number As Integer = 12345
		content.Add($"Number 12345 in words: {number.ToWords()}")
		content.Add($"Ordinal of 21: {21.ToOrdinalWords()}")

		' Pluralization examples
		Dim singular As String = "car"
		content.Add($"Plural of 'car': {singular.Pluralize()}")
		Dim plural As String = "children"
		content.Add($"Singular of 'children': {plural.Singularize()}")

		' Byte size examples
		Dim bytes As Long = 1048576
		content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}")

		Return content
	End Function
End Class
VB   C#

Humanizer C# (How It Works For Developers): Figure 11 - PDF Output

Conclusion

Humanizer is an indispensable library for .NET developers aiming to create applications that present information in a user-friendly and human-readable format. Its wide range of features, from date and time humanization to number and enum formatting, make it a versatile tool for improving the usability of applications. By leveraging Humanizer, developers can save time and effort in implementing custom formatting logic, ensuring that their applications communicate data more effectively to end-users.

Similarly, IronPDF offers comprehensive PDF generation and manipulation capabilities, making it an excellent choice for creating and handling PDF documents in C# projects. Together, Humanizer and IronPDF can significantly enhance the functionality and presentation of .NET applications. For more details on IronPDF licensing, refer to the IronPDF Licensing Information. To explore further, check out our Detailed Tutorial on HTML to PDF Conversion.

< PREVIOUS
TensorFlow .NET (How It Works For Developers)
NEXT >
OpenAPI .NET (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >