How can i convert String like 20100102 into datetime in a formate of dd/MM/yyyy?
5 Answers
IFormatProvider culture = new CultureInfo("en-EN", false); // use your culture info
DateTime dt = DateTime.ParseExact(myDateTimeString, "yyyyMMdd", culture, DateTimeStyles.NoCurrentDateDefault);
yyyyMMdd is input format here.
And then if you wish convert it to string:
String output = String.Format("{0:dd/MM/yyyy}", dt);
2 Comments
Noldorin
Right - except that it probably makes sense either to use
CultureInfo.CurrentCulture or CultureInfo.InvariantCulture dependening on the scenario.JCasso
I changed user override to false. So it uses default now. But it will not cause any problems here even it overrides. Or am I wrong?
string strStartDateMain = "20100102";
string strStartDateFinal = new DateTime(Convert.ToInt32strStartDateMain.Substring(0, 4)), Convert.ToInt32(strStartDateMain.Substring(4, 2)), Convert.ToInt32(strStartDateMain.Substring(6))).ToString("dd/MM/yyyy");
6 Comments
Ashish
I got this answer by doing R&D on that topic. Here If we have a string like "20100102", Than we can get output like "02/01/2010"
Noldorin
Bah, this really isn't the way to do it.
Aaronaught
Custom date parsing FTL. Don't reinvent the wheel.
Jon Skeet
Indeed, this isn't the right way to do it. This will give somewhat cryptic error messages if the format isn't quite right, or if the string is too short.
Ashish
This is only used whene our strStartDateMain will comes in a same range and length.
|