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
in your .NET MVC view, render the UTC time as data attribute.
Then, in your JavaScript code, retrieve the UTC time from the data attribute and convert it to the local time of the user
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.
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