I'm calling .NET's DateTime.ParseExact
with a custom format string along the lines of "MM/dd/yyyy h:mmt"
. This string handles four-digit years but not two-digit years. Is there a way to handle both cases in a single ParseExact call? I've tried "MM/dd/yy h:mmt"
and it only handles the two-digit case.
print(new DateFormat('yyyy/MM/dd'). parse(null)); That's how to parse a String to a DateTime in Dart.
ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.sssZ ) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers.
You can pass an array of format strings for the second parameter on this overload of ParseExact
- this would include both the 2 and 4 year variants.
DateTime.ParseExact(myDateTime,
new []{"MM/dd/yy h:mmt", "MM/dd/yyyy h:mmt"},
CultureInfo.InvariantCulture,
DateTimeStyles.None)
Call the overload of DateTime.ParseExact
that accepts an array of possible formats:
DateTime dt =
DateTime.ParseExact(s, new[] { "MM/dd/yyyy h:mmt", "MM/dd/yy h:mmt" }, null, 0);
For the third argument, pass null
or DateTimeFormatInfo.CurrentInfo
if your date string is localized for the user's current culture; pass DateTimeFormatInfo.InvariantInfo
if your date string is always in the U.S. format.
For the fourth argument, 0 is equivalent to DateTimeStyles.None
.
See the MSDN Library documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With