Reputation: 519
I am working with date function.data comes in different format like
1."2016-01-31"
2."31-01-2016"
3."31/01/2016"
4."2016/01/31"
5."jan 01 2016"
6."2016-01-02 12:00 AM"
Now I want to convert all above mentioned format date to DateTime format YYYY-mm-dd.
I tried many methods but some format shows error message like
'String was not correct format'
'Unable to convert string value to datetime'
I tried,
Datetime date=DateTime.ParseExact(txtdate.Text,'YYYY-mm-dd',CultureInfo.InvariantCulture);
How can I cast/Convert value to datetime format(YYYY-mm-dd) from any format text box value.
mostly I am geting error afterI upload to server(GoDaddy and Microsoft azure).
Can I Use like this
string dateTimes=txtdate.Text;
string[] dateTimes = new string[] { "YYYY-mm-dd", "dd-mm-YYYY","mm/dd/YYYY","yyyy/MM/dd"};
Upvotes: 1
Views: 3644
Reputation: 2668
Your code isn't quite right. The date format string should be surrounded by " (double quotes) and the casing should be like so "yyyy-MM-dd". Also CultureInfo.InvariantCulture
is spelt incorrectly.
Having said that, you shouldn't need to use the ParseExact
function to convert the string to DateTime
format. You can simply use Convert.ToDateTime
Here's some sample code I used to test the Convert.DateTime
function:
string[] dateTimes = new string[] { "2010-02-01", "02-03-2011", "03/04/2012", "2013/05/04", "june 05 2014", "2015-07-06 11:00 AM" };
StringBuilder sb = new StringBuilder();
foreach (string date in dateTimes)
{
DateTime dt = Convert.ToDateTime(date);
sb.AppendLine(dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
}
string convertedDateTimes = sb.ToString();
Using the relevant parts from above, you can change your code to the following:
try
{
Datetime date = Convert.ToDateTime(txtdate.Text.Trim());
string dateString = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
catch (FormatException ex)
{
//Handle the exception. e.g. show a message or print something to the form.
}
Upvotes: 1