0

I am trying to get this date 4th April 2021 12:00 which is todays date into a DateTime object. I am in the UK and the emulator's locale is set to GB summer time and the format looks correct in it's setting page. I have a date as a string:

string dateTimeStr = "08-04-2021 12:00"; I have tried this:

t = DateTime.Parse(dateTimeStr); I get a datetime object of

4th Aug 2021 12:00 How can I parse a date as a string to DateTime and be sure that the month and the day will not be swapped?

Paul Stanley
  • 1,999
  • 1
  • 22
  • 60
  • 1
    Use `ParseExact` and specify the format explicitly. Note that if you have any control over the format, I'd strongly recommend using an ISO date format instead, to avoid ambiguity - that would be 2021-04-08 for April 8th. – Jon Skeet Apr 08 '21 at 07:53

1 Answers1

1
DateTime.ParseExact(dateTimeStr, "dd/MMM/yyyy hh:mm", CultureInfo.InvariantCulture);

you can use ParseExact and mention the date format as per your requirement.

MShah
  • 1,247
  • 9
  • 14
  • 1
    That's not the date format of the string involved though... if the OP uses that string, it will still fail. (Even as a sample format it's not great, given that it uses `hh` instead of `HH` and has no am/pm indicator.) – Jon Skeet Apr 08 '21 at 08:16