Reputation: 2536
i have a question about string conversion. i have a textbox which the user will input with a date in this format (dd/mm/yy).
Now i have to convert it so it is MySQL friendly.
so far this is what i have done
currentExpDate = txtDateStore.txt; //(i.e 25/12/13)
MessageBox.Show(currentExpDate.ToString()); // for debugging
//DateTime dt = DateTime.Parse(currentExpDate);
DateTime dt = DateTime.ParseExact(
currentExpDate,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
string mySQLDate = dt.ToString("yyyy-MM-dd");
How ever it will always throws an error whenever I try to parse it. I get string exception that says string format is one it does not recognize.
If i try to input the date with this format dd/mm/yyyy it works like a charm. Is there any workaround to solve this?
thanks
Upvotes: 2
Views: 1887
Reputation: 54532
I may be missing something here, but creating your DateTime
object using the "dd/MM/yy" Format then
converting the DateTime
to a string using "yyyy-MM-dd" seems to give me a string in the format you are wanting..
To answer your comment I just used the code you posted in your question and changed the first conversion's Format to "dd/MM/yy".
String currentExpDate;
currentExpDate = txtDateStore.Text; //(i.e 25/12/13)
MessageBox.Show(currentExpDate.ToString()); // for debugging
//DateTime dt = DateTime.Parse(currentExpDate);
DateTime dt = DateTime.ParseExact(
currentExpDate,
"dd/MM/yy",
CultureInfo.InvariantCulture);
string mySQLDate = dt.ToString("yyyy-MM-dd");
Upvotes: 3
Reputation: 564413
You should just use the date as a DateTime directly to store in your database. There is no reason to convert it back into a string.
Upvotes: 6