Reputation: 438
I am trying to get date in this format
"yyyy MM dd"
with spaces between them not slashes, but its not working
using (SqlDataReader r = sqlComm.ExecuteReader())
{
if (r.Read())
{
DateTime Date
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
I can't make any change to SQL Stored Procedure at all
EDIT
Sorry it was giving me this for above "25 10 2012 10:00:00:00 AM" or something so I don;t think I was doing it properly, I only want date like this "yyyy MM dd"
Upvotes: 0
Views: 4069
Reputation: 3638
From date to string
var str= date.ToString("yyyy MM dd")
and for string to date
DateTime date = DateTime.ParseExact(string, "yyyy MM dd", CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 2895
Building off of Marc's answer, it seems like you may be a bit confused about how the DateTime
object vs. a string
representation of the date actually work. The DateTime
is just an offset from the starting point.
This line in your code first takes the value from the Date column in your SQL reader, then converts it to a string with the "yyyy/MM/DD"
format, then finally turns that string into a DateTime
object.
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
So as you can see, you're ending up with a DateTime
object, not the display string
you want. If you actually want this code to return just a formatted string
, this is what your final line should look like:
EDIT
= r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
Upvotes: 1
Reputation: 1063338
A DateTime
does not have a format. It is just the "how long since {epoch}", give-or-take some offset/timezone information. If the value in the source is a datetime, then all you need is:
DateTime date = (DateTime)r["Date"];
Then you might format that later at the UI. But to repeat: a DateTime
does not have a format.
Upvotes: 0
Reputation: 460208
So you want this format: "yyyy MM dd" but you use this "yyyy/MM/dd".
Instead:
String dateString = r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
look: http://ideone.com/XecnUP
Upvotes: 0