1

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");
        }
    });
1408786user
  • 1,868
  • 1
  • 21
  • 39
  • http://stackoverflow.com/questions/274826/how-to-get-client-date-and-time-in-asp-net http://stackoverflow.com/questions/13717479/how-to-get-client-current-date-and-time-in-asp-net – Amr Elgarhy May 12 '17 at 10:14
  • As you can see, I have multiple fields and rows so I can't create hidden fields. My table is built dynamically. – 1408786user May 12 '17 at 10:17
  • are you saving the user timezone offset anywhere? if not, you will need to do an ajax call to get the current time on the user browser. – Amr Elgarhy May 12 '17 at 10:20
  • Not yet. But before I do the post to get the results I might be able to put the user's timezone into my model. – 1408786user May 12 '17 at 10:24
  • If you found the solution you can add it as an answer. – Amr Elgarhy May 15 '17 at 09:04

0 Answers0