Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Date - C#

How would I be able to convert a string like "On Monday 25th March 2010..." to 25/03/10? Also, is this possible?

like image 315
Sam Davis Avatar asked Oct 22 '10 16:10

Sam Davis


3 Answers

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.

like image 110
Klaus Byskov Pedersen Avatar answered Oct 18 '22 16:10

Klaus Byskov Pedersen


As klausbyskov points out,DateTime.ParseExactis 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"
like image 29
Ani Avatar answered Oct 18 '22 16:10

Ani


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");
like image 45
tnyfst Avatar answered Oct 18 '22 18:10

tnyfst