'Europe/London time on Blazor Wasm

I've read the docs on timezone updates in .net 6, but I'm failing to understand something!

I want to get the number of hours between "now" (my time) and 10pm tonight (London time).

TimeRemaining = _date.Subtract(DateTime.Now);

With _date being, 10pm tonight (London time).

However DateTime.Now returns a time in UTC, and given we've now moved to BST we're an hour out.

I am trying to use the TimeZoneInfo to get the relevant timezone, however:

TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time") // "The time zone ID 'GMT Standard Time' was not found on the local computer."
TimeZoneInfo.FindSystemTimeZoneById("Europe/London") // "The time zone ID 'Europe/London' was not found on the local computer."

There doesn't appear to be a way to get the time currently in London (taking in to account daylight savings changes etc), but the docs suggest there should be! What am I missing?



Solution 1:[1]

I just tried the following in a Blazor WebAssembly project, inside a .razor file, and it worked just fine:

@code {

    static TimeSpan GetTimeUntil10PMLondon()
    {
        var london = TimeZoneInfo.FindSystemTimeZoneById("Europe/London");
        var time = new TimeOnly(22, 0); // 22:00 = 10:00PM
        var nextTime = GetNextTimeInZone(time, london);
        return nextTime - DateTimeOffset.UtcNow;
    }

    static DateTimeOffset GetNextTimeInZone(TimeOnly time, TimeZoneInfo timeZone)
    {
        // get the time specified, on today's date in the specified time zone
        var now = DateTimeOffset.UtcNow;
        var date = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, timeZone).Date);
        var timeToday = GetDateTimeOffset(date, time, timeZone);

        // return the time today, if it hasn't passed yet
        if (now < timeToday)
            return timeToday;

        // otherwise, return the time tomorrow
        return GetDateTimeOffset(date.AddDays(1), time, timeZone);
    }

    static DateTimeOffset GetDateTimeOffset(DateOnly date, TimeOnly time, TimeZoneInfo timeZone)
    {
        var dateTime = date.ToDateTime(time);
        var offset = timeZone.GetUtcOffset(dateTime);
        return new DateTimeOffset(dateTime, offset);
    }
}

@GetTimeUntil10PMLondon()

You had said that TimeZoneInfo.FindSystemTimeZoneById("Europe/London") didn't work, but it should, and does for me. Perhaps you are not on the current version? This was updated in .NET 6.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Johnson-Pint