-7

What is the best way to convert string (dd/MM/yyyy) to date (MM-dd-YYYY) in C#?

string date = "15/01/2017";
DateTime date1 = DateTime.Parse(date, new CultureInfo("en-CA"));
btnBack.Text = date1.ToString();

I have error

String was not recognized as a valid DateTime.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
M. Rashford
  • 121
  • 1
  • 12

1 Answers1

5

I suggest you use explicit formats in your case, you can do that by using ParseExact to get the DateTime object and then providing the desired format to the ToString overload:

string date = "15/01/2017";
DateTime date1 = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.CurrentCulture);
btnBack.Text = date1.ToString("MM-dd-yyyy");
Zein Makki
  • 29,485
  • 6
  • 52
  • 63