Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Humanizing dates in time zones other than system and UTC #1294

Open
ryno1234 opened this issue Sep 14, 2023 · 2 comments
Open

Humanizing dates in time zones other than system and UTC #1294

ryno1234 opened this issue Sep 14, 2023 · 2 comments

Comments

@ryno1234
Copy link

I'm attempting to humanize a date in the local (to the user) time zone.

  1. We store dates in the DB as UTC.
  2. I want to humanize the dates in the user's local timezone.
  3. I convert the UTC dates to local var localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, usersLocalTimeZone)
  4. Call humanizer localTime .Humanize(false, localNow)
  5. Result is very bizarre and nonsensical (at first glance)

After reviewing the source code it seems that is because the dateToCompareAgainst in is always converted either ToUniversalTime() or ToLocalTime()

    public static string Humanize(this DateTime input, bool? utcDate = null, DateTime? dateToCompareAgainst = null, CultureInfo culture = null)
    {
        var comparisonBase = dateToCompareAgainst.HasValue ? dateToCompareAgainst.Value : DateTime.UtcNow;
        utcDate ??= input.Kind != DateTimeKind.Local;
        comparisonBase = utcDate.Value ? comparisonBase.ToUniversalTime() : comparisonBase.ToLocalTime();

        return Configurator.DateTimeHumanizeStrategy.Humanize(input, comparisonBase, culture);
    }

What is the best course of action to supply 2 dates in any like-timezone and get the the time between them?

@ryno1234
Copy link
Author

ryno1234 commented Sep 14, 2023

Side note: I realize there are reasons this functions like this, however perhaps it should be made more clear in the documentation how the internals work. You apparently cannot simply provide 2 dates and get the humanized value unless the dates are either UTC or Local (local meaning server's time by default). Providing DateTimes that coincide with a time zone other than UTC or Local produce unexpected results.

@hangy
Copy link
Contributor

hangy commented Sep 15, 2023

DateTime.ToLocalTime uses the DateTimeKind to determine if the date needs to be converted at all. I think you may be able to work around the weird behaviour by using DateTime.SpecifyKind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants