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:
Template Item where you can call an Eval option to compute Utc Date.
Change the value of myField server side so that the grid view can bind that. e.g. in your SQL query results.
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);
}
You could convert the time to UTC in your query to pull the data from the database.
In your select clause just use the below.
SELECT DATEADD (HH, 'Your UTC Offset', DateYouWantSelected)
Related
I am using Visual Web Developer Express 2013 and have created a gridview. When I update other values in the grid, I want txtDate to show the time the values were updated.
I set it up as an item template.
<asp:TemplateField HeaderText="txtDate" SortExpression="txtDate">
<itemtemplate><asp:label id="txtDate" runat="server"
text="<%# Bind DateTime.Now.ToString()%>"></asp:label>
</itemtemplate>
</asp:TemplateField>
When I use the above code without Bind - I get the current time displaying. I added Bind so that the current date would insert into the database and I get the following error;
Compiler Error Message: CS1026: ) expected
I'm trying to figure out the best way to insert the date when the values are updated. I also tried adding txtDate as a hidden field but that didn't work either.
Uses GetDate() function directly in the insert query, you don't need to show this to the user, because its just for logging purpose as far as I have understood what you want to do.
I've written an SQL Server stored procedure that, amongst other things, accepts a date parameter:
CREATE PROCEDURE data.addScore
... (some parameters),
#testDate date
AS
On an ASP.NET page I have a textbox with a Calender Extender control (from the AJAX Toolkit) that allows the user to select a date; the date is stored in the textbox in the format DD/MM/YYYY. I have some code that is supposed to execute the stored procedure with the parameters, using the date value from the textbox:
cmd.Parameters["#testDate"].Value = Convert.ToDateTime(((TextBox)li.FindControl("date")).Text);
I know I can definitely get to the textbox's value using ((TextBox)li.FindControl("date")).Text, but for the life of me I can't get it into a format that doesn't throw up one of a few errors, mainly 'Input string was not in the correct format'.
When I run the stored procedure directly on the server I usually bind the parameter like #testDate = 'YYYYMMDD'.
I would suggest you don't store anything in the textbox using regional, ambiguous formats like dd/mm/yyyy. If you use an unambiguous format like YYYYMMDD, you're not going to have any issues. And if users are picking from a calendar control or something, it should be easy to separate the date you present to them from the date you pass to the database.
<asp:Textbox id="date" runat="Server"></asp:Textbox>
<cc1:CalendarExtender ID="calwhendate" runat="server" Enabled="true" Format="YYYYMMDD"
TargetControlID="date"></cc1:CalendarExtender>
Change your Ajax Calendar Control to your desired format
I have a InsertItemTemplate defined in my DeatilView control. Within this template I have a number of fields that the user fills and a number of fields that are filled automatically and the user cannot change them. These values are coming from an object stored in session.
Code looks like this: (I only mention necessary parts, if you need anything more let me know)
<asp:DetailView ... DataSourceID="MyDataSource" ...>
<Fields>
...
<InsertItemTemplate>
// These are the fields filled by the system
<asp:Label ... Text='<%# some value from session object %>' />
<asp:Label ... Text='<%# some value from session object %>' />
// some textboxes here that user fills,
//they use Bind("some data source value here") to send their data to database
...
</InsertItemTemplate>
...
</Fields>
</asp:DetailView>
Now the problem is where I need to actually insert values into database.
Textbox values are sent just alright, but since I haven't bound label values they are not sent to DataSource. So I'm asking how to do this?
An alternative I found was to pass a DefaultValue to DataSet's
respective InsertParameter but I don't know how to fill that area to
get it's value from Session.
Another alternative is to set Parameter's value (not default value)
to be taken from Session, which is possible but this only support
values that are directly within Session, and I'm passing the value of
a property inside an object that's stored in Session. Is there a
way to get this fixed, other than storing values inside Session
directly.
What type of DataSource are you using? I need to know it, because there is few ways to obtain parameters from session depending on type of datasource.
detailView_ItemInserting(object sender, DetailsViewInsertEventArgs e) is called just before inserting the data, you can use detailView.FindControl method in this event to get access to Label controls.
I have a column in the data table called CurrentDate as datatype string (12/2/1983).
When I am displaying on the screen this is showing as 12/2/1983 12:00:00AM.
I am not sure why I am getting timestamp here?
Can anybody help me out?
If you are binding this from a datasource, like a SQL Data Source, you can use CONVERT in your query:
CONVERT(VARCHAR(10),nameOfColumn,101) AS Date
If you need to do this in C#, try the ToShortDateString() method:
string date = myDate.ToShortDateString();
In C# if you convert it to a DateTime object:
DateTime.ToShortDateString();
Are you using data binding to a gridview, formview, or other formatable data source? If so you can simply use the "d" format flag, like below:
<asp:BoundField DataField="MyDate" DataFormatString="{0:d}" HeaderText="My Date" />
An example of its usage within the context of setting a label would be:
MyLabel.Text = DateTime.Now.ToString("A FORMATTING STRING HERE);
Two very useful MSFT posts I use are: "Standard DateTime formatting strings" and "Custom date time formatting strings"
I have an ASP.Net 3.5 page that contains a FormView control, bound to a Business Object using an ObjectDataSource.
One of the properties of the business object is a DateTime type, and I want to do 2 way databinding for this object, including the DateTime property.
I use a custom format for displaying the DateTime property, as shown here:
<asp:TextBox ID="TextBoxDate" runat="server" Text='<%# Bind("Date", "{0:d MMM yyyy HHmm}") %>' />
It displays just fine.
The problem is when I attempt to perform an Update. I get the following exception:
String was not recognized as a valid DateTime.
My ObjectDataSource contains an explicitly set UpdateParameter for this Property, but it doesn't appear to make any difference.
<UpdateParameters>
<asp:Parameter Name="Date" Type="DateTime" />
</UpdateParameters>
What am I doing wrong?
UPDATE:
It turns out that if I change my format string in my Bind expression to
{0:d MMM yyyy HH:mm}
(Notice the colon between the HH and the mm)
... then the two way data-binding works as expected. Sadly, this isn't exactly what I wanted. I was hoping to use the 24 hour clock without a colon, hence my original format string. This is still not working, and I would love to know why? And even better, I'd love to know how I can work-around this shortcoming in the framework, but still do declarative databinding.
Thanks.
You could override the ItemUpdating event of the FormView control and then modify the value for that parameter to make sure it's in the right format. Most likely this means:
get the value from e.NewValues("Date")
Parse the string value into a DateTime object
assign the value back to e.NewValues("Date")
I've had to do something like this in the past with currency fields where people might enter a dollar sign which would cause errors if left alone.
Bind() method, actually provide two way data binding and Eval provide one way data binding
In your scenario, you have to modify date in your formview databound event when you are showing data to user rather setting date format in bind property.
In this way you will get not error when update your fields.