I have a web page, with some fields containing a date and time. The dates and times are stored as UTC.
I would like to convert them to a local date time, if the user is requesting for it (Model.LocalTime set to true)
@foreach (var result in Model.DatabaseData)
{
<tr>
@foreach(var column in Model.Columns)
{
<td>
@if (column.FieldType == "DateTimeOffset" && Model.LocalTime)
{
@(((DateTimeOffset)result.Document[column.FieldName]).LocalDateTime)
}
else
{
@result.Document[column.FieldName]
}
</td>
}
</tr>
}
I assume the local date time is the server's local time and not the end user's local time. Is it possible to get somehow the user's (webbrowser) local time instead of the server local time?
Solution:
@foreach (var result in Model.DatabaseData)
{
<tr>
@foreach(var column in Model.Columns)
{
<td>
@if (column.FieldType == "DateTimeOffset" && Model.LocalTime)
{
<div class="utcTimeToLocal">
@(((DateTimeOffset)result.Document[column.FieldName]).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss"))
</div>
}
else
{
@result.Document[column.FieldName]
}
</td>
}
</tr>
}
Javascript:
$(document).ready(function () {
var timesToConvert = document.getElementsByClassName("utcTimeToLocal")
for (i = 0; i < timesToConvert.length; i++) {
var stillUtc = moment.utc(timesToConvert[i].innerText).toDate();
timesToConvert[i].innerText = new moment(stillUtc).local().format("DD-MM-YYYY HH:mm:ss");
}
});