Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stupid problem with auto-formatting date. 1

Status
Not open for further replies.

oppcos

Programmer
Joined
Dec 1, 2004
Messages
209
Location
US
Hi,
I am connecting to an MS SQL database and requesting a datetime field. When I run the query in SQL Query Analyzer, I get the date back in year-month-day hour:minute:second format. However, when I run the same query from my C# application, I get a string in the format: month/day/year 12hour:minute:second AM/PM.

Is there a way I can force the format of the date field so that I don't have to worry about the local settings of any given computer? I'd prefer the native SQL format displayed by SQL Query Analyzer, so what is converting this into garbage "for me" in C#? Here's a code snippet in case there are any clues there:
Code:
MyTableCommand.CommandText = "select ACCDATE from MYTABLE";
MyTableReader.ExecuteReader();
if(MyTableReader.Read())
  MyTextBox.Text = MyTableReader["ACCDATE"].ToString();

Thanks for any insight.
 
Use always your custom format:
Code:
DateTime dt = MyTableReader["ACCDATE"];// retrieved from the SQL
MyTextBox.Text = dt.ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
If you bind that column to something then add a Convert handler to format the date as you want to be shown in that column:
Code:
MyTextBox.DataBindings["Text"].Format += new ConvertEventHandler(this.MyTexttextBox_FormatDate);
private void MyTexttextBox_FormatDate(object sender, ConvertEventArgs cevent)
{
   cevent.Value = ((DateTime) cevent.Value).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

}
obislavu
 
Yeah, I did basically just that and got around the issue. It annoys me that somewhere in there the runtime thought it would be helpful and thrash the format the database was returning though, especially since I didn't use anything resembling a DateTime object..

Thanks for the accurate response. In the end, I guess I just have to re-force it into the format that I want.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top