Question

I'm trying to find the appropriate format string to parse (exact) the following types of dates:

  • 1-01-01T00:00:00+00:00 - 1 January of 0001
  • 2011-12-14T15:53:40+00:00 - 14 December of 2011

So the year length seems to be variable (1-4 characters).

The format sting I currently use to parse exact is:
c_DateTimeFormatString = "yyyy-MM-ddTHH':'mm':'sszzz"

Obviously this only matches the second string. The first one poped up today. Now we have to match that as well.

Is there a format string to achieve this?

UPDATE #1
I added the actual dates in clear text after the input date strings.

UPDATE #2
Parse exact has an overload that allows for multiple format strings to be passed in. This seems to be the right way.

So the first try was to use:

DateTime.ParseExact("1-01-01T00:00:00+00:00 ", new[] { "yyyy-MM-ddTHH':'mm':'sszzz", "yyy-MM-ddTHH':'mm':'sszzz", "yy-MM-ddTHH':'mm':'sszzz", "y-MM-ddTHH':'mm':'sszzz" }, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal)

But sadly this does ont give the correct result, the first date string is parsed as:
01.01.2001
rather than
01.01.0001

So the question now is what is the correct parsing string to parse year one which is represented with only one digit?

Was it helpful?

Solution

Updated based on comment:

string y = "yyyy-MM-ddTHH':'mm':'sszzz";

string testDate = "1-01-05T00:00:00+00:00".PadLeft(25, '0');
Console.WriteLine(DateTime.ParseExact(testDate, y, CultureInfo.InvariantCulture));
testDate = "2011-12-14T15:53:40+00:00".PadLeft(25, '0');
Console.WriteLine(DateTime.ParseExact(testDate, y, CultureInfo.InvariantCulture));

The output is:

1/5/0001 00:00:00
12/14/2011 15:53:40

OTHER TIPS

You can use an overload of ParseExact to match multiple formats, I believe.

See MSDN.

If the input formats are not all exactly the same, you'll need either to stop using parse exact, or to call it with different format arguments depending on the format of the input data.

I don't believe you need to match a year from 1 to 4 characters but 2 or 4 characters.

For this example

1-01-05T00:00:00+00:00

you would need something like

d-MM-yyTHH':'mm':'sszzz

Try padding your string so that the year is 4 digits long. You should probably add 2, 20 or 201 and not just 0's.

Since you know that you have to support multiple formats, I suggest that you use the TryParseExact method.

If it fails to parse using one format (i.e. it returns false), then try the next format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top