0

I have been looking around the web to find an example that will solve my issue with string convertion to datetime.

I would like to convert en-us (mm/dd/yyyy) to dutch belgium (dd/mm/yyyy) datetime. Could you please give me a working example?

For your information, I have tried Convert.ToDateTime, Parse, TryParse, ParseExact etc, but none was working. I really like an example that will make this conversion, no futile links.


Upate

The error I get is: String was not recognized as a valid DateTime. What I have tried:

----------------
string str = "02/20/2012";
DateTime dt = Convert.ToDateTime(str);
---------------------
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("nl-BE", true);
DateTime theDateTime = DateTime.ParseExact(deliveryDate, "dd/mm/yyyy", theCultureInfo);
Console.WriteLine(dt);
----------------------
var parsed = DateTime.ParseExact("02/20/2012","dd/mm/yyyy", null);
---------------

dateValue = DateTime.Parse(dateString, new CultureInfo("nl-BE", false));

and some other examples which I don't remember them now. But all leading no where.

Imir Hoxha
  • 1,674
  • 6
  • 31
  • 56

2 Answers2

9

Use these method overloads:

and pass a CultureInfo.DateTimeFormat to them:

string enUsDateString = "12/31/2012";
IFormatProvider enUsDateFormat = new CultureInfo("en-US").DateTimeFormat;

DateTime date = DateTime.Parse(enUsDateString, enUsDateFormat);

IFormatProvider nlBeDateFormat = new CultureInfo("nl-BE").DateTimeFormat;
string nlBeDateString = date.ToString(nlBeDateFormat);

This will, however, also include the time component in the output. If you don't want that, try e.g.:

IFormatProvider nlBeDateFormat = new CultureInfo(…).DateTimeFormat.ShortDatePattern;
//                                                                ^^^^^^^^^^^^^^^^^
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
  • Your last line of code gives me this error: Error CS0029 Cannot implicitly convert type 'string' to 'System.IFormatProvider' – user8128167 Jun 14 '18 at 18:51
1

This works fine for me:

DateTime date = 
DateTime.ParseExact("20122018", "dd/MM/yyyy", 
                   CultureInfo.CurrentCulture);
LolliPop
  • 107
  • 1
  • 7