Midhun Mathew
Midhun Mathew

Reputation: 2207

String which is not in datetime format to DateTime

I have a string which is not in a datetime format eg:20160503. How can i change it to Datetime. I tried using Substring. It is working.Is there any more efficient way? Below is what I have right now.

string a = "20160503";
int b = Convert.ToInt32(a.Substring(0, 4));
int c = Convert.ToInt32(a.Substring(4, 2));
int d = Convert.ToInt32(a.Substring(6, 2));
string date = b + "/" + c + "/" + d;
DateTime result = new DateTime();
DateTime.TryParse(date, out result);

Upvotes: 4

Views: 104

Answers (3)

Midhun Mathew
Midhun Mathew

Reputation: 2207

Thanks for your replies. Finaly I ended up using DateTime.TryParseExact

string dateString = "20150503";
DateTime dateValue = new DateTime();
DateTime.TryParseExact(dateString, "yyyyMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);

Upvotes: 1

Christos
Christos

Reputation: 53958

Since you know the exact format of your datetime, you could try to use the ParseExact DateTime's method.

var dt = DateTime.ParseExact(a,"yyyyMMdd",CultureInfo.InvariantCulture);

For further info, please have a look here.

Upvotes: 6

Stack Overflow
Stack Overflow

Reputation: 2774

Try somthing like this:

Define your own parse format string to use.

string formatString = "yyyyMMdd";
string sample = "20160503";
DateTime dt = DateTime.ParseExact(sample,formatString,null);

Upvotes: 3

Related Questions