Search code examples
asp.netgridviewdatabound

Display Local Time in GridView


I have an asp.net gridview bound to the following sql server 2008r2 data source:

<asp:SqlDataSource ID="dsFault" runat="server" DataSourceMode="DataSet" 
 ConnectionString="<%$ ConnectionStrings:ESBExceptionDb %>"
SelectCommand="select * from Fault order by datetime desc"></asp:SqlDataSource>

In my Fault table there is a column called DateTime of type datetime. The values stored in this column are in UTC format and I need them to be displayed in the local timezone for the browser

I have added a template field to the Columns collection of the grid view as follows:

<asp:TemplateField>
  <ItemTemplate>
   <asp:Label ID="lblLocalTime" runat="server" 
    Text='<%# String.Format("{0:f}", Eval("DateTime").ToLocalTime()) %>'>
   </asp:Label>
  </ItemTemplate>    
</asp:TemplateField>

When I browse the page I get the following error:

CS1061: 'object' does not contain a definition for 'ToLocalTime' and no
extension method 'ToLocalTime' accepting a first argument of type 'object' 
could be found (are you missing a using directive or an assembly reference?)

Can anyone please tell me where I've gone wrong?

Thanks, Rob.


Solution

  • The Eval("DateTime") Value that returns from your database is not a C# DataTime object.

    and because the function .ToLocalTime() belongs to the DateTime c# object you can't use it.

    You need to convert the object to string and then use the function .ToLocalTime()

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

    Ones you converted it to DateTime Object, you can use any format available

    For Example

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