0

I am trying to parse a string timestamp of format "yyyyMMddHHmmss" with DateTime.ParseExact(). The catch is I must allow for an hour value of "24" (i.e. hours can be from 0 to 24, where hour 24 denotes hour 0 of the next day (day + 1, hour = 0) Note: I can't control the input values.) and, of course, that results in an exception.
Are there any settings/properties I can set instead of manually parsing/using regex's? If not, any efficient parsing ideas?

ex.

DateTime.ParseExact("20120911240000", "yyyyMMddHHmmss", 
   System.Globalization.CultureInfo.InvariantCulture);
user897052
  • 85
  • 2
  • 8

3 Answers3

3

if you want to do it manually you can use String.Substring() to detect hour values of "24", then use String.Replace, to set that to "00", then parse your date, and then add a day if that's what an hours value of "24" means

1

Sam's solution is good, but since you are using yyyyMMddHHmmss I would do something like:

bool addDay = false;
DateTime result;
string dtToParse = "20120911240000";

if (dtToParse[8] == '2' && dtToParse[9] == '4')
{
    dtToParse = dtToParse.Substring(0, 8) + "00" + dtToParse.Substring(10);
    addDay = true;
}

result = DateTime.ParseExact(dtToParse, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);

if (addDay) { result = result.AddDays(1); }
Trisped
  • 5,705
  • 2
  • 45
  • 58
  • @user897052 I added in your fixes. I did not actually test it, hence the simple problems. If this solved your issue please mark it as the answer. – Trisped Sep 12 '12 at 17:50
  • no worries, a good example any way; thanks
    @Sam I am and Trisped: I used similar code, temporarily, as a solution. My next goal is to use something a bit more robust/dynamic, perhaps utilizing a custom IFormatProvider as Victor Ronin suggested.
    – user897052 Sep 17 '12 at 16:56
0

There is no simple flag to do what you want.

However, here is the way to create custom datetime parser:

How to create and use a custom IFormatProvider for DateTime?

Community
  • 1
  • 1
Victor Ronin
  • 22,758
  • 18
  • 92
  • 184