Here I am using C# and SQL Server 2005. And my problem is, I have table in SQL Server like this
Status ID CreationDate AccNo Amount
1 1001 5/27/2011 7:56:16 PM 100001 686700
1 1002 5/27/2011 7:56:16 PM 10009 40000
when I am retrieving data like select * from tablename
, then the date column will be displayed like below
Status ID CreationDate AccNo Amount
1 1001 2011-05-27 19:56:16.110 100001 686700
1 1002 2011-05-27 20:04:20.470 10009 40000
why it is changing like that and, how to change the date format 2011-05-27 19:56:16.110
to 5/27/2011 7:56:16 PM
?
Thanks, Anuradha J
A datetime column just stores a date and time value. It doesn't apply, nor store, any formatting information.
If you need these datetimes in a particular format for presentation, then you either need to specify that format during SELECT
(by using CONVERT with an appropriate format specifier), or better, leave it up to whatever is consuming the results to perform conversion and formatting.
Looking at the format specifiers available for CONVERT
, I can't actually see one that allows mm/dd/yyyy hh:mm:ss
, so you'd need to perform two conversions, separately, for the date and time components, or as I say, leave it up to your C# code to perform the formatting. Ugly SQL way:
SELECT
Status,
ID,
CONVERT(varchar(16),CreationDate,101) + ' ' +
CONVERT(varchar(16),CreationDate,8) as CreationDate,
AccNo,
Amount
FROM
tablename
answer dont change it the databse, change how you use the data from the database. in your code.
store the retrieved result in a date time object, then you can do anything you want with it. the data is the same.
or write a stored proc that changes the output to what ever you want.
look up time handeling in TSQL.
In the code behind you can do the following. Bring the date without converting it into string.
DateTime dt;
string Temp1 = "Your Date from database";
if (DateTime.TryParse(Temp1, out dt))
{
// If it is a valid date
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.