If you tried to create a new DateTime in code using:
DateTime convertedDate = DateTime.Parse("17/12/2014");
you would get a run-time error, and DateTime.TryParse would also not work:
DateTime convertedDate;
if (DateTime.TryParse("17/12/2014", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out convertedDate))
{
textBox1.Text = convertedDate.ToString(dateOutputFormat);
}
else
{
textBox1.Text = "conversion fail";
}
You need to use 'TryParseExact
CultureInfo provider = CultureInfo.InvariantCulture;
string dateInputFormat = "dd/mm/yyyy";
string dateOutputFormat = "dd MMMM yyyy";
private string stringToDate(string inputDate)
{
DateTime convertedDate;
if (DateTime.TryParseExact(inputDate, dateInputFormat, provider, DateTimeStyles.AssumeUniversal, out convertedDate))
{
return convertedDate.ToString(dateOutputFormat);
}
else
{
return "Invalid date conversion: " + inputDate;
}
}
private void TestStringToDateConversion_Click(object sender, EventArgs e)
{
textBox1.Text = stringToDate("17/12/2014");
}