skip to Main Content

I need to display the datetime received in CET to the local time of user by using javascript in a .NET MVC application. How can this be done?

<table>
    <thead>
        <tr>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-utc-time="@item.ScheduledTime?.ToUniversalTime().ToString("o")">@item.ScheduledTime.HasValue ? item.ScheduledTime.Value.ToUniversalTime() : "N/A"</td>
        </tr>
    </tbody>
</table>
function convertUtcToLocal() {
    document.querySelectorAll('[data-utc-time]').forEach(function (element) {
        const utcTime = element.getAttribute('data-utc-time');
        if (utcTime) {
            const localTime = new Date(utcTime).toLocaleString('en-GB', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            });
            element.textContent = localTime;
        }
    });
}

This is the code I tried I added a class for each datetime and got the utc time using ToUniversalTime() and then used ToLocaleString() to convert the UTC time to local time of user but this does not work

2

Answers


  1. in your .NET MVC view, render the UTC time as data attribute.

    <div class="utc-time" data-utc-time="@Model.UtcTime.ToString("yyyy-MM-ddTHH:mm:ss")"></div>
    

    Then, in your JavaScript code, retrieve the UTC time from the data attribute and convert it to the local time of the user

    function convertUtcToLocal() {
    document.querySelectorAll('.utc-time').forEach(function (element) {
        const utcTime = element.getAttribute('data-utc-time');
        if (utcTime) {
            const localTime = new Date(utcTime);
            const localTimeString = localTime.toLocaleString();
            element.textContent = localTimeString;
        }
    });
    

    then call convertUtcToLocal();

    Make sure that the UTC time is properly formatted in the ISO 8601 format (yyyy-MM-ddTHH:mm:ss) when rendering it in the data attribute.

    Login or Signup to reply.
  2. Make sure the input is correct and parseable.

    According to what I can find

    @item.ScheduledTime?.ToUniversalTime().ToString("o")

    would translate to 2024-04-02T12:48:00.0000000Z

    This one correctly shows me 14:48 in The Netherlands in CEST

    So you need to tell us what is "wrong" with your output

    const localTime = new Date('2024-04-02T12:48:00.0000000Z').toLocaleString('en-GB', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
    console.log(localTime)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search