在GridView中显示当地时间

问题描述 投票:0回答:6
asp.net gridview databound
6个回答
3
投票

从数据库返回的

Eval("DateTime")
Value 不是 C#
DataTime
对象。

并且因为函数

.ToLocalTime()
属于
DateTime
c# 对象,所以你不能使用它。

您需要将对象转换为字符串,然后使用函数

.ToLocalTime()

<asp:TemplateField>
  <ItemTemplate>
   <asp:Label ID="lblLocalTime" runat="server" 
    Text='<%# Convert.ToDateTime(Eval("DateTime")).ToLocalTime() %>'>
   </asp:Label>
  </ItemTemplate>    
</asp:TemplateField>

将其转换为

DateTime
对象,您可以使用任何可用的格式

例如

Text='<%# Convert.ToDateTime(Eval("DateTime")).ToString("dd/MM/yyyy") %>'

2
投票

除了其他答案之外,请记住 ToLocalTime() 将返回服务器本地时间,而不是您请求的浏览器本地时间。


0
投票

尝试这样

<%# Eval("DateTime", "{0:T}")%>

<asp:Label ID="lblLocalTime" runat="server" 
    Text='<%# Eval("DateTime", "{0:T}")%>'>
   </asp:Label>

0
投票

这样就可以了!尝试一下。

<asp:TemplateField HeaderText="Account Created">
   <ItemTemplate>
      <asp:Label ID="lblLocalTime" runat="server" 
         Text='<%# Convert.ToDateTime(Eval("CreateDate", "{0:g}")).ToLocalTime() %>'>
      </asp:Label>
   </ItemTemplate>    
</asp:TemplateField>

0
投票

看起来没有干净简单的方法可以做到这一点,奇怪!到目前为止提到的答案尝试将日期转换为服务器时区,而不是客户端/浏览器的时区。即,如果服务器位于美国而客户端位于印度,您将看不到印度时区的日期时间,它将是美国时区的日期时间。

其中的重复有更好的答案。基本上,您必须执行以下操作之一 -

  • 将客户端时区信息发送到服务器并在那里进行适当的转换。最好发送时区名称而不是时区偏移量,因为时区偏移量可能因 DST 而异。您可以使用 Intl.DateTimeFormat().resolvedOptions().timeZone 发送时区名称。
  • 将 UTC 日期字符串发送至 客户端并让它使用 javascript 进行转换(新 日期(ISOUTCDateString))。这就是 WCF 中发生的情况。

0
投票

谢谢你。它工作完美。它对我很有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.