3

I have a string which contains date in yyyyMMdd format. I want to convert that date into system date format, using ConvertTo.DateTime() method or any other simple method.

I've used:

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                    Culture, DateTimeStyles.None, out resultDt);

it doesn't return anything, Actually I am troubled with Culture info. I don't know in which Culture it exist.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Sachin Kalia
  • 1,027
  • 14
  • 24

3 Answers3

5

You should almost certainly be specifying CultureInfo.InvariantCulture - but at the moment that code doesn't look like it would compile at all... it looks like you're trying to do a mix of ParseExact and TryParseExact, and you're not specifying the format string...

Try:

DateTime date = DateTime.ParseExact(time, "yyyyMMdd",
                                    CultureInfo.InvariantCulture);

Or if you want to use TryParseExact:

DateTime date;
bool success = DateTime.TryParseExact(time, "yyyyMMdd",
                                      CultureInfo.InvariantCulture,
                                      DateTimeStyles.None,
                                      out date);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Just use this:

DateTime theTime = DateTime.ParseExact(time, "yyyyMMdd",
                                       CultureInfo.InvariantCulture);
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0
string format = "yyyyMMdd";
DateTime date = DateTime.ParseExact(input, format, 
                    CultureInfo.CurrentCulture, DateTimeStyles.None);

or multiple date formats:

string[] formats = {"yyyyMMdd", "dd/MM/yyyy"};
DateTime date = DateTime.ParseExact(input, formats, 
                    CultureInfo.CurrentCulture, DateTimeStyles.None);
Peter
  • 27,590
  • 8
  • 64
  • 84
  • Hi Peer Thanks for you initiation on this. I need the culture local id for this kind of date format . I get the date value at runtime. As string time = "RunTime Value";20110714 DateTime theTime= DateTime.ParseExact(time, Culture, DateTimeStyles.None, out resultDt); for the above given code i have used culture with different date string such as dd//mm/yyyy however in another scenario it comes in yyyyMMdd format.So i am quite interested in Culture info of such type of date format. looking forword with your updates:) Regards Sachin Kalia – Sachin Kalia Jul 14 '11 at 09:58
  • You should have a look at: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx, are you in a web or application scenario? If you ask a date from a user it is best to use a DateTime control instead of a TextBox. – Peter Jul 14 '11 at 10:07