I'm trying to use a GridView
to show a DateTime
value. So far I have been able to show the data using the format string that I want by using:
<asp:GridView ID="myGrid" ... >
<Columns>
<asp:BoundField DataField="myField" DataFormatString={0:MM/dd/yyyy hhmmss} ... />
...
</Columns>
...
</asp:GridView>
The problem I'm having now is that this is always being shown as local time. My users will be expecting it to always be shown as UTC, regardless of where they are. Is there some way I can force the GridView
to show what the UTC time would be, instead of the local time?
For example, I have found out that in vb.net, to convert a string to a date I can tell it to use universal time with:
Dim myDateAsString as String = "03/31/2014 19:00"
Dim myDate as DateTime = DateTime.ParseExact(myDateAsString, "MM/dd/yyyy HH:mm", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AssumeUniversal)
I'm looking for something similar to the .AssumeUniversal
part that I can use when I set up my GridView
in asp.
I hope what I'm asking is clear. If not I can try to elaborate more, if someone let's me know what isn't clear.
UPDATE:
The DataSource
for my GridView
is a DataSet
that is filled by a SELECT
query that just pulls data from my database. Since the field I'm interested in here is a DateTime
field in my database, I am assuming it will still be a DateTime
when it gets assigned as the DataSource
. Is that correct?
It looks to me like the only code related to filling the GridView
is
myGrid.DatqaSource = mySQLObject.sel_from_table(vars)
myGrid.DataBind()
Where mySQLObject.sel_from_table(vars)
will return a DataSet
as described above. The answers so far have suggested that I need to change the data to UTC before sending it to the GridView
- Where/how should that be done? Do I have to change it in my query somehow? Or in the DataSet
before I assign it as the DataSource
?
The grid view is merely a display mechanism. It'll display whatever value you pass it in the format you specified. If you want to change the value itself (Utc Date) then 2 options are:
Either ways, your server side code needs to convert the date into UTC (ToUniversalTime() or DateTime.UtcNow etc.) and send it across for display.
here is how you can do using TemplateField.
in your ASPX
<asp:TemplateField HeaderText="My Fields">
<ItemTemplate>
<asp:Label runat="server" text='<%# GetUtcFormattedDate((DateTime)Eval("myField")) %>' />
</ItemTemplate>
</asp:TemplateField>
In your code behind, you can have a static method
public static string GetUtcFormattedDate(DateTime date)
{
return date.ToUniversalTime().ToString(YOUR_DATE_FORMAT_STRING);
}