Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 231
Midhun Mathew Avatar asked Dec 25 '22 06:12

Midhun Mathew


1 Answers

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.

like image 94
Christos Avatar answered Dec 29 '22 06:12

Christos