I have a console project that retrieves some data from a database. It is using a connection string. When I run the project I get date as 1/1/2010 12:00:00 AM
, but I want to get only the date - like 1/1/2010
.
The code looks like this:
string sql = "SELECT * FROM Employees";
SqlCommand cmd = new SqlCommand(sql, sqlConnection);
SqlDataReader dr = cmd.ExecuteReader();
// this is for header
string _fname = "First Name";
string _lname = "Last Name";
string _dob = "DOB";
Console.WriteLine("{0} | {1} | {2}", _fname.PadRight(10), _lname.PadRight(10), _dob.PadRight(10));
while (dr.Read())
{
Console.WriteLine("{0} | {1} | {2}",
dr["FirstName"].ToString().PadRight(10),
dr["LastName"].ToString().PadRight(10),
// Below is what I want to format.
dr["DOB"].ToString().PadRight(10)
}
dr.Close();
I tried:
dr["DOB"].ToString(MM-dd-yyyy).PadRight(10)
dr["DOB"].Date.ToString(MM-dd-yyyy).PadRight(10)
However none of them works.
When reading data using database, how do I format date?
Please try with below code snippet.
Old code:-
dr["DOB"].ToString().PadRight(10)
New code:-
Option 1
dr.GetDateTime(columnIndex).ToString("dd/MM/yyyy");
Option 2
Convert.ToDateTime(dr["DOB"]).ToString("dd/MM/yyyy")
You can also get it converted from SQL. Update the query:
SELECT *, CONVERT(VARCHAR(10),DOB, 103) as FormattedDOB from Employees
and your c#:
dr["FormattedDOB"].ToString().PadRight(10);
Why dont you try this:
String.Format("{0:MM-dd-yyyy}", <YourDate>)
You can use custom date and time formats to achieve your desired Format. Your code could look like so:
var sql = "SELECT * FROM Employees";
var cmd = new SqlCommand(sql, sqlConnection);
SqlDataReader dr = cmd.ExecuteReader();
var _fname = "First Name";
var _lname = "Last Name";
var _dob = "DOB";
Console.WriteLine("{0} | {1} | {2}", _fname.PadRight(10),_lname.PadRight(10),_dob.PadRight(10));
while (dr.Read())
{
dt = (DateTime)dt["DOB"];
Console.WriteLine("{0} | {1} | {2}",
dr["FirstName"].ToString().PadRight(10),
dr["LastName"].ToString().PadRight(10),
dt.ToString("MM/dd/yy").PadRight(10));
}
dr.Close();
Possibly the return value of dr["DOB"]
is string and not a date. in this case you could convert it to date and then .ToString("MM/dd/yy")
or you could simply find the index of " " and then split the string like so:
var str = (string)dr["DOB"]
Console.Write(str.Split(' ')[0]);
This will return: 1/1/2010
You Need to parse string value to DateTime first. Try Something like this
string datestr ="1/1/2010 12:00:00 AM";
DateTime dateTime;
var ds = DateTime.TryParse(datestr,out dateTime);
string outstr = dateTime.ToString("MM/dd/yyyy");
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.