How should I parse these DateTime strings?

I have two formats of a date: 11-Apr-2018 & 11-04-2018.

For 11-04-2018 I use "dd-MM-yyyy" with DateTime.TryParseExact with success.

For 11-Apr-2018 I use "dd-MMM-yyyy" but the result is 01/01/2018.

Which format should I try parse against for the date value 11-Apr-2018?

Here is my code:

CultureInfo enZA = new CultureInfo("en-ZA");
var formatStrings = new string[] { "yyyy-MM-dd", "dd-MMM-yyyy" };
DateTime formattedDate;
DateTime.TryParseExact(dateToFormat, 
                       formatStrings, 
                       enZA, 
                       DateTimeStyles.None, 
                       out formattedDate);

Upvotes: 1

Views: 51

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

I suggest DateTime.ParseExact where you can specify several formats:

DateTime date = DateTime.ParseExact(
  valueToParse,
  new string[] { 
    "d-MM-yyyy",     // try this first
    "d-MMM-yyyy" },  // on failure try this next
  CultureInfo.GetCultureInfo("en-US"),
  DateTimeStyles.AssumeLocal);

For instance

  string[] tests = new string[] {
    "11-04-2018",
    "11-Apr-2018",
  };

  var result = tests
    .Select(test => DateTime
      .ParseExact(test,
                  new string[] { "d-MM-yyyy", "d-MMM-yyyy" },
                  CultureInfo.GetCultureInfo("en-US"),
                  DateTimeStyles.AssumeLocal))
    .Select(date => date.ToString("dd : MM : yyyy"));

 Console.Write(string.Join(Environment.NewLine, result));

Outcome:

 11 : 04 : 2018
 11 : 04 : 2018

Upvotes: 4

Fuzzybear
Fuzzybear

Reputation: 1418

dd-MMM-yyyy should be correct

var foo =  DateTime.Now;
foo.ToString("dd-MMM-yyyy");

worked for me, I use the tostring maybe that is behaving differently to the TryParseExact ?

Upvotes: 0

Related Questions