0

I have multiple input in string like the following:-

  1. 05/09/2017
  2. 05/09/2017 13:56 PM
  3. 05/09/2017 01:56 PM
  4. 05/09/2017 13:56:00
  5. 05/09/2017 01:56:00 PM

Now how do i convert the above examples into DateTime format (dd/MM/yyyy hh:mm:ss tt).

I have already tried

  1. ParseExact - It gives error when the user gives 05/09/2017 as value (because the format doesn't match)

    DateTime.ParseExact(ValueByuser, "dd/MM/yyyy HH:mm:ss tt", null);

  2. TryParse - The problem with it is that it uses the LocalFormat of the computer like if the computer has set to "MM/dd/yyyy" then it produces output in the same format

    DateTime.TryParse(DatePass, out Dtp);

Agent_Spock
  • 1,107
  • 2
  • 16
  • 44

2 Answers2

2

You could use the ParseExact or TryParseExact overload that accepts an array of formats, and pass all the formats you want to support. E.g.

var formats = new[]
{
    "dd/MM/yyyy",
    "dd/MM/yyyy HH:mm",
    "dd/MM/yyyy HH:mm tt",
    "dd/MM/yyyy HH:mm:ss",
    "dd/MM/yyyy HH:mm:ss tt",
};

You should also specify CultureInfo.InvariantCulture as your format provider, e.g.:

var d = DateTime.ParseExact(s, 
  formats, CultureInfo.InvariantCulture, DateTimeStyles.None);

I believe the above will match all your sample inputs except the second (05/09/2017 13:56 PM) which I assume is a typo and should be 05/09/2017 13:56 without the am/pm indicator.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • Agreed. Since the input format will not match any locale (it uses 24H clock with am/pm indicator which nobody in the world uses!) then the only solution is to explicitly list all supported formats individually. – Matthew Watson Sep 05 '17 at 08:40
2

You could do something like the following;

string dd = "05 / 09 / 2017 13:56:00";
string newdate = dd.Replace("/", "-");
DateTime DT = DateTime.Parse(newdate);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Tom
  • 12,928
  • 2
  • 15
  • 31