0

I am getting a string as 10 Apr, 2014 - 09:27 and I want it to compare with the current DateTime to see if its lower or above.

The above gives an error as Not recognized as Valid DateTime.

How can I convert this properly?

Do I need to format the date first to some format etc?

Hexie
  • 3,955
  • 6
  • 32
  • 55
confusedMind
  • 2,573
  • 7
  • 33
  • 74
  • Custom format: http://stackoverflow.com/questions/919244/converting-string-to-datetime-c-net – noobob Apr 08 '14 at 07:59

3 Answers3

4

Use DateTime.ParseExact or DateTime.TryParseExact(if the format can be invalid).

This works with your sample:

DateTime dt = DateTime.ParseExact("10 Apr, 2014 - 09:27", "dd MMM, yyyy - HH:mm", CultureInfo.InvariantCulture);

I'm using CultureInfo.InvariantCulture to ensure that it works with english month names even if the current culture is different. You need to change HH to hh if the hours aren't in 24h format.

To compare with the current time use DateTime.Now:

if(dt > DateTime.Now)
{
    // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You can use the DateTime.ParseExact function and give it the custom format your are expecting it to be in.

samy
  • 14,832
  • 2
  • 54
  • 82
0

You can use this link to accomplish what you are asking for:

How to compare DateTime in C#?

Code Snippet (from the link supplied):

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
// The example displays the following output:
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM

Hope that helps.

Community
  • 1
  • 1
Hexie
  • 3,955
  • 6
  • 32
  • 55