Vi Vek
Vi Vek

Reputation: 157

Need to convert following string into time format

I have the following two dates in string format.

1. 06 Mar 2013 
2. 26 Mar 2013

I need to compare those two dates i.e if (06 Mar 2013 < 26 Mar 2013)

Is there any built-in function to convert string into C# Date and Time format?

Upvotes: 1

Views: 224

Answers (3)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

Yes there is. Try DateTime.Parse and DateTime.ParseExact methods. Here is the code sample:

string first = "06 Mar 2013";
string second = "26 Mar 2013";

DateTime d1 = DateTime.Parse(first);
DateTime d21 = DateTime.Parse(second);

var result = d1 > d21; //false

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460028

Use DateTime.ParseExact in the following way:

DateTime dt = DateTime.ParseExact(str, "dd MMM yyyy", CultureInfo.InvariantCulture);

Demo

CultureInfo.InvariantCulture is needed to ensure that it will be parsed successfully even if the current culture does not have english month names.

Upvotes: 0

Habib
Habib

Reputation: 223187

You need to parse these two dates to DateTime Object, using DateTime.ParseExact with format dd MMM yyyy and then compare both.

string str1 = "06 Mar 2013";
string str2 = "26 Mar 2013";

DateTime dt1 = DateTime.ParseExact(str1, "dd MMM yyyy", null);
DateTime dt2 = DateTime.ParseExact(str2, "dd MMM yyyy", null);
if(dt1 < dt2)
{
  //dt1 is less than dt2
}

You can also use the format d MMM yyyy, with single d which would work for both single digit and double digit day (e.g. 02 ,2 and 12 etc)

Upvotes: 2

Related Questions