数据库中保存为 UTC 格式的 “时间”,BIND 到 GRIDVIEW 中后, 如何显示为本地格式的时间?
可以在RowDataBound的时候,将时间从GMT转成Local如下:

   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // Convert UTC to local times (DateTime field is column 1)
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DateTime TempDateTime;

            // convert text in GridView cell to DateTime
            TempDateTime = DateTime.Parse(e.Row.Cells[1].Text);
           
            // convert UTC to LocalTime
            TempDateTime = TempDateTime.ToLocalTime();

            // replace text in GridView cell
            e.Row.Cells[1].Text = TempDateTime.ToString();
        }
    }

如果希望在事件中处理问题.也可以在Gridview中加入一个Templet的列,然后在在其中加入一个Label 然后对显示的text 内容进行处理 如下。

<asp:Label ID="lbl1" runat="server" Text=<%# System.DateTime.Parse(DataBinder.Eval(Container.DataItem, "LastModified").ToString() + " GMT") %> ></asp:Label>

最后还有一种方法就是直接在返回的DataTable中进行处理,通过循环将所有的GMT时间转成当前的时间,来解决此问题。不过如果是这么处理的话,如果需要对数据update的话需要特别留意,需要先将本地时间再转回到GMT时间,然后插入到数据库中。

其实在系统中保存的时间格式使用的一直都是UTC,所以Local的时间一般只是用于显示的时候。所以RowDataBound的时候,将UTC的时间格式通过ToLocalTime()方法转换为当地时间,这个做法就是比较标准的方法了。因为这样作能够很好的将显示层与数据层区分开,当需要把时间写回到DataSet的时候再次将时间在转为UTC时间。

如果这样依旧不能很好的满足您的需求的话,建议您可以重载GridView控件,当遇到DateTime类型的数据时,自动执行DateTime.toLocalTime()的方法,以达到显示本地时间的目的,然后当修改数据的时候,再使用toUTCTime()方法,将时间转换为UTC时间从新写回到数据库中。

相关文章:

  • 2021-05-19
  • 2022-12-23
  • 2022-02-01
  • 2021-12-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-03-29
猜你喜欢
  • 2021-08-03
  • 2022-01-08
  • 2022-12-23
  • 2023-03-29
  • 2022-01-10
  • 2021-05-24
  • 2022-12-23
相关资源
相似解决方案