Search code examples
c#asp.net-coreblazor-server-sideunix-timestampdata-conversion

Converting Data Receiving Time (dt) in Unix, UTC format from API Call into traditonal date format using Blazor Server-Side Weather App


Apologies if this has been answered adequately elsewhere, I just can't seem to piece together the solution from the many existing posts regarding unix conversions. I have built a crude Blazor server-side weather forecast app that calls a weather forecast API and returns a seven-day forecast, with each day distinguished by an unix, utc format date (ex:{"dt":1631293200}). I have been able to successfully display the results from the call as follows:

 <tbody>
            @foreach (var w in forecast.daily)
            {
                <tr>
                    <td>@w.dt</td>
                    <td>@w.temp?.min F°</td>
                    <td>@w.temp?.max F°</td>
                    <td>@w.temp?.day F°</td>
                </tr>
            }
        </tbody>

Is there a simple way I can translate that "dt" result into a more recognizable date, like, "Friday, Sept 13th" or "09/13/21", in a Blazor server-side app using C#?


Solution

  • This how to convert unix utc to local time.

    You can modify accordingly.

    The unix timestamp is just how many seconds have passed since the epoch.

    public static class TimeUtils
    {
            public static DateTime UnixTimeStampToDateTime(double unixTimeStamp )
            {
                // The unix timestamp is how many seconds since the epoch time
                // so just substract
                var epochDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                epochDateTime = epochDateTime .AddSeconds( unixTimeStamp ).ToLocalTime();
                return dateTime;
            }
    }
    

    You can then convert that DateTime to any string format you wish

    For example

    myDateTime.ToLongDateString()
    

    So if you had for example that method inside a static class called TimeUtils and assuming that the w.dt is a double:

            <tbody>
                @foreach (var w in forecast.daily)
                {
                    <tr>
                        <td>@(TimeUtils.UnixTimeStampToDateTime(w.dt).ToLongDateString())</td>
                        <td>@w.temp?.min F°</td>
                        <td>@w.temp?.max F°</td>
                        <td>@w.temp?.day F°</td>
                    </tr>
                }
            </tbody>
    

    As pointed out by @Alexander Petrov there is also another way using

    DateTimeOffset.FromUnixTimeSeconds
    

    Which returns a DateTimeOffset object. This can also be an alternative.