Working with time and date in C# using the Humanizer library

Working with time and date in C# using the Humanizer library

Introduction

In the previous article, we explained how to work with Humanizer, a free and open source .NET library that offers a set of extension methods and utilities for formatting and manipulating strings, numbers, dates, times, time intervals, numbers and quantities in a convenient for human perception in the form. We’ve seen how Humanizer can help us convert camelCase and Pascal strings into readable text, format numbers and make them look user-friendly, and convert words to plural and singular.

Working with time and date is one of the most common and boring tasks in any application. Users expect to see the date and time in a format that is easy to understand and relevant to the context. For example, users would like to see something like “2 hours ago” instead of “2023-12-01 12:14:53” or “tomorrow at 10:00 AM” instead of “2023-12-02 10:00:00” . Additionally, users may also have different preferences for time and date formats depending on their culture, language, and location.

The purpose of this article is to show you how to use Humanizer to take time and date handling in your C# projects to the next level. I will talk about how to transform objects DateTime and TimeSpan in a form convenient for human perception (for the sake of brevity, we will use the term “humanize” below), how to configure humanization parameters and how to combine humanization of lines with time/date. We’ll also look at some real-world use cases and examples of how Humanizer can improve the time and date user experience.

Humanization of DateTime objects

Object DateTime represents a specific point in time, such as the current time and date, or a time and date in the past or future. Humanizer provides several extension methods for rendering objects DateTime to a human-readable format.

Format DateTime into an easy-to-read form

One of the easiest ways to humanize an object DateTime – Use the extension method Humanize, which returns a string representing the time and date in natural language. Example:

using Humanizer;

DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1);
DateTime tomorrow = now.AddDays(1);
DateTime nextWeek = now.AddDays(7);

Console.WriteLine(now.Humanize()); // сейчас
Console.WriteLine(yesterday.Humanize()); // вчера
Console.WriteLine(tomorrow.Humanize()); // через 23 часа
Console.WriteLine(nextWeek.Humanize()); // через 6 дней

As you can see, the method Humanize returns a string that is easy to understand and depends on the current time and date. It also takes into account various temporal relations such as today, yesterday, tomorrow, and future or past dates.

Display relative time (eg “2 hours ago”)

Another way to humanize the object DateTime – Use the extension method Humanize with a boolean parameter indicating whether or not to display the relative time. A relative time is a string that represents how much time has passed since or will pass until a specific point in time. Example:

using Humanizer;

DateTime anHourAgo = DateTime.Now.AddHours(-1);
DateTime anHourLater = DateTime.Now.AddHours(1);

Console.WriteLine(anHourAgo.Humanize()); // час назад
Console.WriteLine(anHourLater.Humanize()); // через 59 минут

As you can see, relative time is useful when you need to show how close or far certain times and dates are from the present moment, and absolute time is when you need to show the exact date and time.

DateTime humanization options

Humanizer also allows you to customize objects DateTime humanization parameters such as culture, accuracy, maximum and minimum units of measurement. You can use the Humanize extension method with the object HumanizeOptions, in which the desired parameters are specified. Example:

using System.Globalization;
using Humanizer;

DateTime now = DateTime.Now;
DateTime twoHoursAgo = now.AddHours(-2);

// Указываем другую культуру
Console.WriteLine(twoHoursAgo.Humanize(culture: new CultureInfo("fr-FR"))); // il y a 2 heures

As you can see, an option culture allows you to use a different language and format to humanize the string.

Humanization of TimeSpan objects

Object TimeSpan represents a time interval, such as the duration of an event or the difference between two dates and times. Humanizer provides several extension methods for humanizing objects TimeSpan in a user-friendly format.

Convert TimeSpan to a user-friendly format

One of the easiest ways to humanize an object TimeSpan – Use the extension method Humanize, which returns a string representing the time interval in natural language. Example:

using Humanizer;

TimeSpan oneHour = TimeSpan.FromHours(1);
TimeSpan oneMinute = TimeSpan.FromMinutes(1);
TimeSpan oneSecond = TimeSpan.FromSeconds(1);
TimeSpan oneMillisecond = TimeSpan.FromMilliseconds(1);

Console.WriteLine(oneHour.Humanize()); // 1 час 
Console.WriteLine(oneMinute.Humanize()); // 1 минута 
Console.WriteLine(oneSecond.Humanize()); // 1 секунда
Console.WriteLine(oneMillisecond.Humanize()); // 1 миллисекунда

As you can see, the method Humanize returns a string that depends on the specified time interval and is easy to understand. It also takes into account nuances such as singular and plural forms, as well as indefinite and definite articles.

Handling durations (eg “2 days, 5 hours and 30 minutes”)

Another way to humanize the object TimeSpan – Use the extension method Humanize with a parameter indicating the duration of the time interval, i.e. displayed. we can specify the precision with which the time interval will be output. Example:

using Humanizer;

TimeSpan twoDays = TimeSpan.FromDays(2);
TimeSpan twoHours = TimeSpan.FromHours(2);
TimeSpan twoMinutes = TimeSpan.FromMinutes(2);
TimeSpan twoSeconds = TimeSpan.FromSeconds(2);
TimeSpan twoMilliseconds = TimeSpan.FromMilliseconds(2);

Console.WriteLine(twoDays.Humanize()); // 2 дня
Console.WriteLine(twoHours.Humanize()); // 2 часа
Console.WriteLine(twoMinutes.Humanize()); // 2 минуты
Console.WriteLine(twoSeconds.Humanize()); // 2 секунды
Console.WriteLine(twoMilliseconds.Humanize()); // 2 милисекунды

As you can see, working with duration is useful when you want to show exactly the number of units of a time interval, and limiting to one unit is when you want to show only the largest unit of a time interval.

TimeSpan humanization options

Humanizer also allows you to customize objects TimeSpan humanization parameters such as culture, accuracy, maximum and minimum units of measurement. You can use the extension method Humanize with the object HumanizeOptionsin which the necessary parameters will be indicated:

using System.Globalization;
using Humanizer;
using Humanizer.Localisation;

TimeSpan twoDays = TimeSpan.FromDays(2.75);

// Указываем другую культуру 
Console.WriteLine(twoDays.Humanize(culture: new CultureInfo("fr-FR"))); // 2 часа

// Указываем другую точность
Console.WriteLine(twoDays.Humanize(precision: 3)); // 2 дня, 18 часов

// Указываем другую максимальную единицу измерения
Console.WriteLine(twoDays.Humanize(maxUnit: TimeUnit.Hour)); // 66 часов

// Указываем другую минимальную единицу измерения
Console.WriteLine(twoDays.Humanize(minUnit: TimeUnit.Minute)); // 2 дня

As you can see, the parameter culture allows you to use a different language and format to humanize the string. Parameter precision allows you to specify how many time units to include in the humanized string. Parameters max unit and min unit allow you to specify the largest and smallest units of time measurement.

Combining string humanization and DateTime

Humanizer allows you to humanize strings and date/time objects not only separately, but also to combine them into a single entity. You can use the Humanize extension method with a string that contains placeholders for date/time objects, and Humanizer will automatically replace them with humanized strings. Example.

using Humanizer;

DateTime now = DateTime.Now;
DateTime twoHoursAgo = now.AddHours(-2);

// Использование заполнителей для объектов даты/времени
Console.WriteLine("The current time is {0}", now.Humanize()); // Текущее время сейчас 
Console.WriteLine("The last update was {0}", twoHoursAgo.Humanize()); // Последнее обновление было 2 часа назад

As you can see, the method Humanize with string containing placeholders for date/time objects allows you to combine string and date/time humanization in a simple and elegant way. You can use any number of placeholders and any format for date/time objects and Humanizer will handle them accordingly.

Real examples of use

Humanizer can help you improve your own experience with date and time in your C# projects in a number of ways. Here are some real-world use cases and examples of how Humanizer can make a difference:

  • Messages in social networks: You can use Humanizer to display the date and time of social media posts in a relative and human-friendly way, such as “2 hours ago” or “yesterday”. This will help users quickly understand how long ago a message was sent, making their lives a little easier.

  • Notifications and reminders: With Humanizer, you can send messages and reminders to users in a natural and user-friendly way, such as “tomorrow at 10:00 AM” or “in 15 minutes.” This will help users better remember and plan their tasks, and avoid confusion and mistakes.

  • Journals and reports: With Humanizer, you can format the date and time in logs and reports in an easy-to-read and consistent manner, such as “12/1/2023 4:14:53 PM” or “2 days, 5 hours and 30 minutes.” This will help users better analyze and compare data, and find and fix problems faster.

  • Calendars and schedules: With Humanizer, you can display the date and time on calendars and schedules in a clear and concise manner, such as “Monday, December 1, 2023” or “2 hours 30 minutes”. This will help users better view and manage their events, and avoid conflicts and overlaps.

Conclusion

In this article, we learned how to use Humanizer to conveniently work with date and time in our C# projects. We considered how to humanize objects DateTime and TimeSpan, how to configure humanization options, and how to combine string and date/time humanization. We’ve also covered some real-world use cases and examples of how Humanizer can improve users’ experience with date and time.

Humanizer is a powerful and versatile library that helps you format and manipulate strings, numbers, dates, times, time intervals, numbers and quantities in a human-friendly way. It will help you save time and effort, and also make your code more readable and convenient. It can also improve user experience and make your apps more interesting and engaging.

I hope you enjoyed this article and learned something new and useful. Thank you for attention.

Finally, we invite you to the open class “Databases: relational databases and working with them”, you can sign up on the online course page.

Related posts