Converting date to proper format
I have a table in an ms-sql database which contains dates in a column like so:
SqlCommand command = new SqlCommand(); //connection info here sql2 = "(select statement here); command.CommandText = sql2; dates["Entry"] = command.ExecuteScalar();
So, this fills up the grid w/ the correct dates, however, I’m trying to format it so I just get the month, day, and year, not the time after, with slashes. So like this:
I’ve tried converting it to date time and using:
I’ve tried using a reader instead and doing something like:
which also didn’t work. I just can’t seem to find the correct way to do this. Any tips would be great.
Edit: Here’s the sql2 statement:
sql2 = "select max(day) as day from users u join days d on d.User_ID = u.id where u.ActiveUser = 1 and u.id = " + Users["ID"].ToString();
This is just getting the most recent date a user has entered stuff in.
The date that shows up in the grid is like so “3/12/2013 12:00:00 AM”.
Edit 3: The .ExecuteScalar() function seems to be formatting the date automatically to “3/12/2013 12:00:00 AM” type of format.
4 Solutions collect form web for “Converting date to proper format”
Just change your format to
dates["Entry"] = ((DateTime)command.ExecuteScalar()).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
2010-06-24 If you want to display a DateTime like this you just pass a format string of “yyyy-mm-dd” so it would look like this:
string Date = new DateTime(2010, 6, 24).ToString("yyyy-mm-dd");
You can read more about what formats you can output on a DateTime at this link:
You can also use ToShortDateString() function to cut off the time string-:
Try out following in the sql:
select CONVERT(datetime, column_name, 101) from table_name
101 – is datetime style. You may find all styles by the link
Also in code behind:
Hope it helps