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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With