Question

I'm trying to parse LocalDateTime values using Noda Time LocalDateTimePattern.Parse() method. I'm in the US. The following call to Parse() fails:

var localDateTimePattern = LocalDateTimePattern.Create("G", CultureInfo.InvariantCulture);
var parseResult = localDateTimePattern.Parse("4/10/2014 3:03:11 PM");

This fails as well

var localDateTimePattern = LocalDateTimePattern.Create("g", CultureInfo.InvariantCulture);
var parseResult = localDateTimePattern.Parse("4/10/2014 3:03:11 PM");

What am I doing wrong? My idea was to be able to parse DateTime string presented in a standard to a current culture format.

Using BCL like the following works:

DateTime dateTime;
var parseResult = DateTime.Parse("4/10/2014 3:03:11 PM");

(Related formatting question was asked here: http://goo.gl/Q8DYTB)

Was it helpful?

Solution

A few things:

  • Passing null to a IFormatProvider, or a CultureInfo parameter, will use the current culture, not the invariant culture. It's equivalent to passing CultureInfo.CurrentCulture.

  • For methods like DateTime.Parse or ToString that have overloads that omit the format provider, null is assumed - which again, maps to the current culture, not the invariant culture.

  • In the invariant culture, the "G" format is MM/dd/yyyy HH:mm:ss. You must pass two digits (using a leading zero if necessary) in all fields (except year, which is 4 of course), and you must pass time in 24 hour format. AM/PM indicators are not allowed.

  • If you wish to use "G" with the current culture, then pass CultureInfo.CurrentCulture, or if you know the culture you want, then pass that specific culture.

  • The "g" format is the same as "G", except it doesn't include seconds.

  • Noda Time is identical to the normal types in all of the above, except that it doesn't allow for null to be passed. I believe this is intentional, to avoid this sort of confusion.

So, your methods are failing because you are passing only one-digit for a month, and passing 12-hour time format, but the invariant culture doesn't allow that. Try instead:

var pattern = LocalDateTimePattern.Create("G", CultureInfo.InvariantCulture);
var parseResult = pattern.Parse("04/10/2014 15:03:11");

Or perhaps:

var pattern = LocalDateTimePattern.Create("G", CultureInfo.CurrentCulture);
var parseResult = pattern.Parse("4/10/2014 3:03:11 PM");

Or if your current culture is not in that format, then use a specific culture:

var culture = CultureInfo.CreateSpecificCulture("en-US");
var pattern = LocalDateTimePattern.Create("G", culture);
var parseResult = pattern.Parse("4/10/2014 3:03:11 PM");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top