-1

I know similar questions have been asked such as here: DateTime string conversion with both month name and AM/PM

Indeed, I am having a very similar problem but even when I follow the answers to the question above it still doesn't seem to work for me. I'm trying to execute the following piece of code:

dateTime = DateTime.ParseExact(dateString + " " + yearString + " " + 
timeString, "MMMM dd yyyy HH:mm tt", 
System.Globalization.CultureInfo.InvariantCulture);

Where 'dateString' is "September 25" 'yearstring' is "2017" 'timestring' is "6:30 PM"

The Exception that gets thrown when executing this code is FormatException String was not recognized as a valid DateTime. In my date string above I am inserting a single white space for each use of quotes.

L.B
  • 114,136
  • 19
  • 178
  • 224
andy_coder
  • 145
  • 1
  • 4
  • 10
  • 2
    Post the dateString as it is. – L.B Aug 26 '17 at 18:28
  • Thanks for the formatting help – andy_coder Aug 26 '17 at 18:29
  • 1
    Use `h` instead of `HH`. `HH` is the 24-hour-clock hour, so it makes little sense to use it in conjunction with `tt`. I very much doubt that the full month name has anything to do with this. – Jon Skeet Aug 26 '17 at 18:32
  • Thanks @JonSkeet, however, I've made that change and am still getting the error. – andy_coder Aug 26 '17 at 18:36
  • 1
    @andy_coder `DateTime.ParseExact("September 25 2017 6:30 PM", "MMMM dd yyyy h:mm tt", CultureInfo.InvariantCulture)` just works fine. Your error (you didn't _even_ mentioned what it was exactly) might come somewhere else. Also it would be better to check your string(s) doesn't have _any_ invisible character using with a unicode explorer. – Soner Gönül Aug 26 '17 at 18:46
  • 1
    Please show that in the question then, ideally in the form of a [mcve] - there's no need to do string concatenation when you can just show the example with the complete hard-coded string. – Jon Skeet Aug 26 '17 at 18:54
  • So I just got it to work. Your comment, @SonerGönül, might of helped me. I made 2 changes. I changed H to lower case h and I created the full date time string first in a new varaible and then passed that in the datetime.parseexact() function. – andy_coder Aug 26 '17 at 19:02

1 Answers1

0

I got this to work by doing two things (probably the second item more relevant). I changed upper case H in my format string to lower case h. Additionally I saved the full date time string first in a separate variable and then passed that in to the DateTime.ParseExact() function. Maybe other users can answer WHY this worked.

Thanks Stack Overflow community.

andy_coder
  • 145
  • 1
  • 4
  • 10