Humanizer
Humanizer copied to clipboard
Neglect hours in DateTime
Hi! Regarding the magazine's issue date, I would like to get "today" or "yesterday" instead of "3 hours ago" or "15 hours ago". I do not want to have hours at all (because nobody cares of hours). How can I achieve this with Humanizer?
@evgeni-nabokov Humanizer doesn't support that out-of-the-box. You'd have to create your own IDateTimeHumanizeStrategy
implementation, and set that in the configuration. Something like:
public class DaysOnlyHumanizeStrategy : IDateTimeHumanizeStrategy
{
private static readonly IDateTimeHumanizeStrategy DefaultStrategy =
new DefaultDateTimeHumanizeStrategy();
public string Humanize(DateTime input, DateTime comparisonBase, CultureInfo culture)
{
// Remove hours
var inputDate = input.Date;
var comparisonBaseDate = comparisonBase.Date;
// You'd have to localize this string yourself in your app, if needed
// because the formatters that come with Humanizer do not have the word "today"
if (inputDate == comparisonBaseDate) return "today";
return DefaultStrategy.Humanize(inputDate, comparisonBaseDate, culture);
}
}
// Example
Configurator.DateTimeHumanizeStrategy = new DaysOnlyHumanizeStrategy();
Console.WriteLine(DateTime.UtcNow.Date.Humanize()); // today
Console.WriteLine(DateTime.UtcNow.Date.AddDays(-1).Humanize()); // yesterday
Console.WriteLine(DateTime.UtcNow.Date.AddDays(1).Humanize()); // tomorrow
As of this writing, Humanizer is on version 2.7.2, and the word today
is not present in the Resources, which means you'd have to localize this word within the library or app that implements the IDateTimeHumanizeStrategy
, if your app has more than one language.
Relates to #545
I found that for "yesterday" one could use this:
dt.Date.Humanize()
It considers only the date and ignores the time, so gives "yesterday".