A few things:
Passing
null
to aIFormatProvider
, or aCultureInfo
parameter, will use the current culture, not the invariant culture. It's equivalent to passingCultureInfo.CurrentCulture
.For methods like
DateTime.Parse
orToString
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 isMM/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 passCultureInfo.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");