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

Introduction

IN previous article We learned how to work with Humanizer, a free, 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 values ​​in a human-readable way. form. We saw how Humanizer can help us convert camel notation (camelCase) and Pascal style (PascalCase) strings into human-readable text, format numbers and dates in a user-friendly way, and convert words to plural and singular.

Working with time and date is one of the most common and tedious tasks in any application. Users expect to see the date and time in a format that is easy to understand and contextual. 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 manipulation in your C# projects to the next level. I'll talk about how to transform objects DateTime And TimeSpan into a human-readable format (for the sake of brevity, we will use the term “humanize” below), how to configure humanization parameters, and how to combine humanization of strings with time/date. We'll also look at some real-life use cases and examples of how Humanizer can improve the user experience regarding time and date.

Humanizing DateTime Objects

An 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 casting objects DateTime to a human-readable format.

Formatting a DateTime into a human-readable format

One of the easiest ways to humanize an object DateTime – use extension method Humanize, which returns a string representing the time and date in natural language. For 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 time relationships such as today, yesterday, tomorrow, and future or past dates.

Display relative time (for example, “2 hours ago”)

Another way to humanize an object DateTime – use extension method Humanize with a boolean parameter indicating whether to display relative time or not. Relative time is a string that represents how much time has passed since or will pass until a particular moment. For 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 a particular time and date is from the present moment, and absolute time is useful when you need to show an exact date and time.

DateTime Humanization Options

Humanizer also allows customization for objects DateTime such humanization parameters as culture, accuracy, maximum and minimum units of measurement. You can use the Humanize extension method with an object HumanizeOptions, which indicates the desired parameters. For 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, the option culture allows you to use a different language and format to humanize a string.

Humanizing TimeSpan Objects

An 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 into a user-friendly format.

Converting TimeSpan to a user-friendly format

One of the easiest ways to humanize an object TimeSpan – use extension method Humanize, which returns a string representing a time interval in natural language. For 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 (for example, “2 days, 5 hours and 30 minutes”)

Another way to humanize an object TimeSpan – use extension method Humanize with a parameter indicating the displayed duration of the time interval, i.e. we can specify with what accuracy the time interval will be displayed. For 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 a specific number of units of a time interval, and limiting it to one unit is useful when you want to show only the largest unit of a time interval.

TimeSpan Humanization Options

Humanizer also allows customization for objects TimeSpan such humanization parameters as culture, accuracy, maximum and minimum units of measurement. You can use extension method Humanize with object HumanizeOptionswhich will indicate the required parameters:

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 a string. Parameter precision allows you to specify how many time units to include in the humanized string. Options max unit And min unit allow you to specify the largest and smallest units of time.

Combining String Humanization and DateTime

Humanizer allows you to humanize strings and date/time objects not only individually, but also to combine them into a single whole. You can use the Humanize extension method with a string containing placeholders for date/time objects, and Humanizer will automatically replace them with humanized strings. For 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 a 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 process them accordingly.

Real use cases

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

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

  • Notifications and Reminders: With Humanizer, you can send notifications 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 remember and plan their tasks better and avoid confusion and mistakes.

  • Logs and reports: With Humanizer, you can format date and time in logs and reports in a readable and consistent way, 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 in calendars and schedules in a clear, crisp manner, such as “Monday, December 1, 2023” or “2:30 a.m.” 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 easily work with date and time in our C# projects. We looked at how to humanize objects DateTime And TimeSpan, how to configure humanization options and how to combine string and date/time humanization. We also looked at some real-life use cases and examples of how Humanizer can improve users' date and time experience.

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-readable way. It will help you save time and effort, and also make your code more readable and convenient. It can also improve the user experience and make your applications more interesting and attractive.

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

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

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *