I am writing an extension method to parse a specific string which contains a date and a time into a DateTime
object using the DateTime.TryParseExact()
Method.
An example of the format is as follows: "29 November 2013 20:04"
The code I am using to parse it to a DateTime is:
public static DateTime MyToDateTime(this string value)
{
DateTime converted;
DateTime.TryParseExact(value, "dd MMM yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
return converted;
}
The result is always DateTime.Min
(i.e 0001-01-01 00:00:00.000
)
I cant figure out what is wrong with my format string. Any help would be appreciated.
A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.
A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime. ToString using the 'z' format specifier, which will include a local time zone offset in the output.
TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.
from your comments:
MMM
.HH
instead of hh
.Try This:
DateTime.TryParseExact(value, "dd MMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
There are two problems I see:
November
is not a 3-letter month—that would be Nov
. To parse a full date name, use MMMM
.HH
.This should work:
DateTime.TryParseExact(value, "dd MMMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
Further Reading
Try adding an extra M and a capital H
DateTime.TryParseExact(value, "dd MMMM yyyy H:mm", .....
See here for more info: How can I visualize the way various DateTime formats will display?
MMM
stands for the abbreviated name of the month, so it's not what you're looking fore. Use MMMM
instead.
Find all custom Date and Time format string on MSDN: Custom Date and Time Format Strings.
You should also check the value returned by TryParseExact
method. It returns false
when parse failed and true
when it was performed without any problems.
And hh
should be HH
to parse hour part of your input.
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