How would I be able to convert a string like "On Monday 25th March 2010..." to 25/03/10? Also, is this possible?
DateTime.TryParse() is a good place to start. I recommend TryParse
over Parse
since text strings can be tricky. With Parse
you'll have to include error catching. The algorithm is fairly sophisticated, but not infallible!
You can use DateTime.ParseExact
, but I think you have to strip "On " before trying to parse it.
EDIT According to the format documentation you probably do not have to strip "On " afterall.
var theDate = DateTime.ParseExact(theString, "On dddd ddth MMMM yyy",
CultureInfo.InvariantCulture);
Should do it.
As klausbyskov points out,DateTime.ParseExact
is the way to go.
I believe the correct format string you need is (tested):
@"On dddd dd\t\h MMMM yyyy..."
The 't' and 'h ' characters need to be escaped since they carry special significance ('AM/PM' and 'hour' respectively).
Note though, that the parser will carry out some validation checks. In particular, your example will fail to parse since the 25th of March, 2010 happened to be a thursday; try it with:
"On Thursday 25th March 2010..."
As for the the output, the format string you need is:
"dd/MM/yy"
You can't do this with date parsing alone. Any format string that works for the 25th is going to fail for the 22nd or 23rd. Personally, I'd use a regular expression to strip the date into something parsable.
string s = "On Monday 25th March 2010";
string pattern = @"^[^0-9]+(\d+)(\w\w)?";
string clean = Regex.Replace(s, pattern,@"$1");
string result = DateTime.ParseExact(clean,"dd MMMM yyyy",
CultureInfo.InvariantCulture)
.ToString("dd/MM/yy");