Humanizer C# (How It Works For Developers)
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 the 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
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
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
using System;
class HumanizerDemo
{
static void Main()
{
DateTime pastDate = DateTime.Now.AddDays(-3);
// Humanize the past date, which converts it to a relative time format
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
// Humanize the future date, presenting it in relative time
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"
Console.WriteLine("Humanized Past Date: " + humanizedTime);
Console.WriteLine("Humanized Future Date: " + futureHumanizedTime);
}
}
using System;
class HumanizerDemo
{
static void Main()
{
DateTime pastDate = DateTime.Now.AddDays(-3);
// Humanize the past date, which converts it to a relative time format
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
// Humanize the future date, presenting it in relative time
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"
Console.WriteLine("Humanized Past Date: " + humanizedTime);
Console.WriteLine("Humanized Future Date: " + futureHumanizedTime);
}
}
Imports System
Friend Class HumanizerDemo
Shared Sub Main()
Dim pastDate As DateTime = DateTime.Now.AddDays(-3)
' Humanize the past date, which converts it to a relative time format
Dim humanizedTime As String = pastDate.Humanize() ' Output: "3 days ago"
Dim futureDate As DateTime = DateTime.Now.AddHours(5)
' Humanize the future date, presenting it in relative time
Dim futureHumanizedTime As String = futureDate.Humanize() ' Output: "in 5 hours"
Console.WriteLine("Humanized Past Date: " & humanizedTime)
Console.WriteLine("Humanized Future Date: " & futureHumanizedTime)
End Sub
End Class
The Humanizer extension method automatically handles different time units and even adjusts for grammatical correctness.
Humanizing TimeSpans
Humanizer can also humanize TimeSpan
objects, making it easy to display durations in a readable format.
Example: Humanizing TimeSpan
using System;
class TimeSpanHumanizerDemo
{
static void Main()
{
TimeSpan timeSpan = TimeSpan.FromMinutes(123);
// Humanizing the TimeSpan into hours and minutes
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
Console.WriteLine("Humanized TimeSpan: " + humanizedTimeSpan);
}
}
using System;
class TimeSpanHumanizerDemo
{
static void Main()
{
TimeSpan timeSpan = TimeSpan.FromMinutes(123);
// Humanizing the TimeSpan into hours and minutes
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
Console.WriteLine("Humanized TimeSpan: " + humanizedTimeSpan);
}
}
Imports System
Friend Class TimeSpanHumanizerDemo
Shared Sub Main()
Dim timeSpan As TimeSpan = System.TimeSpan.FromMinutes(123)
' Humanizing the TimeSpan into hours and minutes
Dim humanizedTimeSpan As String = timeSpan.Humanize(2) ' Output: "2 hours, 3 minutes"
Console.WriteLine("Humanized TimeSpan: " & humanizedTimeSpan)
End Sub
End Class
Working with Numbers
Humanizer provides several methods to convert numbers into human-readable words and to handle ordinal numbers.
Example: Converting Numbers to Words
using System;
class NumberHumanizerDemo
{
static void Main()
{
int number = 123;
// Convert number to words
string words = number.ToWords(); // Output: "one hundred and twenty-three"
Console.WriteLine("Number in Words: " + words);
}
}
using System;
class NumberHumanizerDemo
{
static void Main()
{
int number = 123;
// Convert number to words
string words = number.ToWords(); // Output: "one hundred and twenty-three"
Console.WriteLine("Number in Words: " + words);
}
}
Imports System
Friend Class NumberHumanizerDemo
Shared Sub Main()
Dim number As Integer = 123
' Convert number to words
Dim words As String = number.ToWords() ' Output: "one hundred and twenty-three"
Console.WriteLine("Number in Words: " & words)
End Sub
End Class
Example: Converting Numbers to Ordinals
using System;
class OrdinalHumanizerDemo
{
static void Main()
{
int number = 21;
// Convert number to ordinal words
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
Console.WriteLine("Ordinal Number: " + ordinal);
}
}
using System;
class OrdinalHumanizerDemo
{
static void Main()
{
int number = 21;
// Convert number to ordinal words
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
Console.WriteLine("Ordinal Number: " + ordinal);
}
}
Imports System
Friend Class OrdinalHumanizerDemo
Shared Sub Main()
Dim number As Integer = 21
' Convert number to ordinal words
Dim ordinal As String = number.ToOrdinalWords() ' Output: "twenty-first"
Console.WriteLine("Ordinal Number: " & ordinal)
End Sub
End Class
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
using System;
class PluralizationDemo
{
static void Main()
{
string singular = "car";
// Pluralize the word
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
// Singularize the word
string singularForm = word.Singularize(); // Output: "person"
Console.WriteLine("Plural of 'car': " + plural);
Console.WriteLine("Singular of 'people': " + singularForm);
}
}
using System;
class PluralizationDemo
{
static void Main()
{
string singular = "car";
// Pluralize the word
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
// Singularize the word
string singularForm = word.Singularize(); // Output: "person"
Console.WriteLine("Plural of 'car': " + plural);
Console.WriteLine("Singular of 'people': " + singularForm);
}
}
Imports System
Friend Class PluralizationDemo
Shared Sub Main()
Dim singular As String = "car"
' Pluralize the word
Dim plural As String = singular.Pluralize() ' Output: "cars"
Dim word As String = "people"
' Singularize the word
Dim singularForm As String = word.Singularize() ' Output: "person"
Console.WriteLine("Plural of 'car': " & plural)
Console.WriteLine("Singular of 'people': " & singularForm)
End Sub
End Class
Humanizer handles irregular pluralizations and singularizations as well, making it robust for various use cases.
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
using System;
public enum MyEnum
{
FirstValue,
SecondValue
}
class EnumHumanizerDemo
{
static void Main()
{
MyEnum enumValue = MyEnum.FirstValue;
// Humanizing enum to a readable format
string humanizedEnum = enumValue.Humanize(); // Output: "First value"
Console.WriteLine("Humanized Enum: " + humanizedEnum);
}
}
using System;
public enum MyEnum
{
FirstValue,
SecondValue
}
class EnumHumanizerDemo
{
static void Main()
{
MyEnum enumValue = MyEnum.FirstValue;
// Humanizing enum to a readable format
string humanizedEnum = enumValue.Humanize(); // Output: "First value"
Console.WriteLine("Humanized Enum: " + humanizedEnum);
}
}
Imports System
Public Enum MyEnum
FirstValue
SecondValue
End Enum
Friend Class EnumHumanizerDemo
Shared Sub Main()
Dim enumValue As MyEnum = MyEnum.FirstValue
' Humanizing enum to a readable format
Dim humanizedEnum As String = enumValue.Humanize() ' Output: "First value"
Console.WriteLine("Humanized Enum: " & humanizedEnum)
End Sub
End Class
This method can be particularly useful for displaying user-friendly labels in UIs.
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
using System;
class ByteSizeHumanizerDemo
{
static void Main()
{
long bytes = 1048576;
// Humanize bytes to a readable size format
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"
Console.WriteLine("Humanized Byte Size: " + humanizedBytes);
}
}
using System;
class ByteSizeHumanizerDemo
{
static void Main()
{
long bytes = 1048576;
// Humanize bytes to a readable size format
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"
Console.WriteLine("Humanized Byte Size: " + humanizedBytes);
}
}
Imports System
Friend Class ByteSizeHumanizerDemo
Shared Sub Main()
Dim bytes As Long = 1048576
' Humanize bytes to a readable size format
Dim humanizedBytes As String = bytes.Bytes().Humanize() ' Output: "1 MB"
Console.WriteLine("Humanized Byte Size: " & humanizedBytes)
End Sub
End Class
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.
using System;
class DateTimeOffsetHumanizerDemo
{
static void Main()
{
DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
// Humanize DateTimeOffset
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"
Console.WriteLine("Humanized DateTimeOffset: " + humanizedDateTimeOffset);
}
}
using System;
class DateTimeOffsetHumanizerDemo
{
static void Main()
{
DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
// Humanize DateTimeOffset
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"
Console.WriteLine("Humanized DateTimeOffset: " + humanizedDateTimeOffset);
}
}
Imports System
Friend Class DateTimeOffsetHumanizerDemo
Shared Sub Main()
Dim dateTimeOffset As DateTimeOffset = System.DateTimeOffset.Now.AddDays(-2)
' Humanize DateTimeOffset
Dim humanizedDateTimeOffset As String = dateTimeOffset.Humanize() ' Output: "2 days ago"
Console.WriteLine("Humanized DateTimeOffset: " & humanizedDateTimeOffset)
End Sub
End Class
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:
Open Your Project in Visual Studio:
- Launch Visual Studio and open your existing C# project or create a new one.
Open the NuGet Package Manager:
- Right-click on your project in the Solution Explorer.
- Select "Manage NuGet Packages…" from the context menu.
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.
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 PDFGenerationDemo
{
static void Main()
{
// Instantiate the PDF renderer
var renderer = new ChromePdfRenderer();
// Generate humanized content
List<string> content = GenerateHumanizedContent();
// HTML content template for the PDF
string htmlContent = "<h1>Humanizer Examples</h1><ul>";
// Build the list items to add to the HTML content
foreach (var item in content)
{
htmlContent += $"<li>{item}</li>";
}
htmlContent += "</ul>";
// Render the HTML into a PDF document
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF to a file
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF document generated successfully: output.pdf");
}
/// <summary>
/// Generates a list of humanized content examples
/// </summary>
/// <returns>List of humanized content as strings</returns>
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 PDFGenerationDemo
{
static void Main()
{
// Instantiate the PDF renderer
var renderer = new ChromePdfRenderer();
// Generate humanized content
List<string> content = GenerateHumanizedContent();
// HTML content template for the PDF
string htmlContent = "<h1>Humanizer Examples</h1><ul>";
// Build the list items to add to the HTML content
foreach (var item in content)
{
htmlContent += $"<li>{item}</li>";
}
htmlContent += "</ul>";
// Render the HTML into a PDF document
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF to a file
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF document generated successfully: output.pdf");
}
/// <summary>
/// Generates a list of humanized content examples
/// </summary>
/// <returns>List of humanized content as strings</returns>
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 PDFGenerationDemo
Shared Sub Main()
' Instantiate the PDF renderer
Dim renderer = New ChromePdfRenderer()
' Generate humanized content
Dim content As List(Of String) = GenerateHumanizedContent()
' HTML content template for the PDF
Dim htmlContent As String = "<h1>Humanizer Examples</h1><ul>"
' Build the list items to add to the HTML content
For Each item In content
htmlContent &= $"<li>{item}</li>"
Next item
htmlContent &= "</ul>"
' Render the HTML into a PDF document
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF to a file
pdf.SaveAs("output.pdf")
Console.WriteLine("PDF document generated successfully: output.pdf")
End Sub
''' <summary>
''' Generates a list of humanized content examples
''' </summary>
''' <returns>List of humanized content as strings</returns>
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
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.
Frequently Asked Questions
What is Humanizer in C#?
Humanizer is a .NET library that simplifies the process of displaying data in a human-readable format, such as converting dates to relative time strings, pluralizing words, and formatting numbers as words.
How do I install Humanizer in a C# project?
You can install Humanizer via NuGet Package Manager Console with the command 'Install-Package Humanizer' or using the .NET Core CLI with 'dotnet add package Humanizer'.
Can Humanizer format TimeSpan objects?
Yes, Humanizer can format TimeSpan objects to display durations in a human-readable format, such as '2 hours, 3 minutes'.
What is an example of humanizing relative time using Humanizer?
Using Humanizer, you can convert a DateTime object to a relative time string like '3 days ago' or 'in 5 hours' using the Humanize method.
How does Humanizer handle pluralization and singularization?
Humanizer provides methods to pluralize and singularize words, handling both regular and irregular forms, such as converting 'car' to 'cars' or 'people' to 'person'.
Can Humanizer work with enums?
Yes, Humanizer can convert enum values to human-readable strings, which is useful for displaying user-friendly labels in interfaces.
What functionalities does the PDF library offer for C# projects?
The library allows developers to create, read, edit, and extract content from PDF files, with features like HTML to PDF conversion, document merging, and adding watermarks using IronPDF.
How do I install the PDF library in a C# project?
You can install the library using the NuGet Package Manager by searching for IronPDF in the 'Browse' tab and clicking 'Install'.
What are the performance considerations when using Humanizer?
Humanizer is designed to be efficient, but for applications requiring high performance with large datasets or real-time processing, it's important to assess the impact of frequent humanization operations.
How can Humanizer and the PDF library be used together?
Humanizer can be used to generate human-readable content, which can then be rendered into a PDF document using IronPDF, allowing for the creation of user-friendly PDF reports.