在ASP.net中继器中显示客户端日期/时间,值存储在UTC中

时间:2019-01-24 15:43:52

标签: asp.net timezone repeater

我有一个LINQ to Entities查询并加载了带有文件列表以及何时上传的ASP Repeater。他们正在显示UTC日期/时间,但我需要它来显示客户时间。

var files = db.Files
              .Where(f => f.IsAvailable == true && f.IsArchived == showTeamArchived && f.FileTypeID == 1 && f.ProjectID == projectid)
              .Select(f => new { f.ProjectID, f.UserID, f.FolderID, FileName = f.FileName.Replace(".sqlite", ""), FileID = f.FileID, f.AspNetUser.Email, f.DateCreated, f.LastUpdated, Status = f.IsArchived == true ? "Archived" : "" });

f.LastUpdated是我要格式化的日期。

<asp:Repeater ID="rptTeamFiles" runat="server">
   <ItemTemplate>
    <tr>
      <td><%#Eval("LastUpdated")%></td>
                                            ....

1 个答案:

答案 0 :(得分:0)

当为转发器触发OnPreRender事件时,我能够完成此操作。使用Moment-Timezone javascript,我通过特定类遍历跨度,并将日期/时间转换为用户本地时区。

ASP.Net

protected void rptTeamFiles_OnPreRender(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "localtime" + dtCount++, "<script>showLocalDateTime();</script>", false);
    }

JavaScript

function showLocalDateTime() {

        var spans = document.getElementsByTagName('span');
        var l = spans.length;

        for (var i = 0; i < l; i++) {
            var spanClass = spans[i].getAttribute("class");
            if (spanClass == "localdatetime") {
                var utc = moment.tz(spans[i].innerHTML, "UTC");
                var local = utc.clone().tz(moment.tz.guess());
                spans[i].innerHTML = local.format('MMM Do YYYY, h:mm a');

            }
        }
    }