首页 > 解决方案 > Converting a string pulled from the internet into a DateTime

问题描述

I am making a program that scrapes the internet and populates a class with all of the information I'm scraping for. I have a DateTime property that needs to be populated from the string I am pulling in. The string that comes in looks like this :9:53a ET 08/13/18.

I have tried using DateTime.ParseExact() to try and convert this string into a DateTime, using the following format string: "h:mmt ET mm/dd/yy"

So the call looks like this: var lastTime = DateTime.ParseExact(listValue[0].InnerText, format, provider);

Where InnerText is just the text that I am trying to convert, Format is the string I specified above, and the provider is en-US.

I get the following exception when trying to execute this line: String was not recognized as a valid DateTime.

How would I format this string to convert it to a DateTime correctly?

标签: c#datetimeparsing

解决方案


Calling

DateTime.ParseExact("9:53a ET 08/13/18".ToUpper(), "h:mmt ET MM/dd/yy", null)

Returns a correctly parsed date. a is not recognized as a AM/PM identifier because it is lowercase (hence the toUpper), and mm/dd/yy should be MM/dd/yy since mm (lowercase is minutes.


推荐阅读