Reputation: 47
I try to parse my string to datetime, but I get a FormatException.
string date = "27.02.2017 13:03:16 Uhr";
action.Date =
DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Does somebody has any idea?
Upvotes: 0
Views: 223
Reputation: 6783
The problem is the "Uhr" at the end of the input. If you specify your format like this, the input must match the format.
After some people add "Uhr" and some people don't, I recommend to extract the relevant part using a regex.
using System.Text.RegularExpressions;
Match m = Regex.Match( @"/([\d]{2}\.[\d]{2}\.[\d]{4} +[\d]{2}\:[\d]{2}\:[\d]{2})/", date);
if (m != null)
date = m.Groups[0].Value;
else
// Something wrong with the input here
And then (unless m is null) you can use this string as a valid input for your ParseExact-part in most cases. But be aware that the regex does not perform any range-checks, so an input like Montag, 99.99.9999 99:99:99 Uhr
would lead to the date string 99.99.9999 99:99:99
which matches the regex, but is not a valid DateTime anyway.
Upvotes: 1
Reputation: 186803
You have to escape Uhr
suffix:
string date = "27.02.2017 13:03:16 Uhr";
action.Date = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss 'Uhr'",
CultureInfo.InvariantCulture);
Upvotes: 5