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.

5
  • You want string to string conversion? Commented Aug 17, 2012 at 18:22
  • DateTime should support a CultureInfo. See: stackoverflow.com/questions/313781/… Commented Aug 17, 2012 at 18:24
  • 2
    I assure you that ParseExact is workng fine. Commented Aug 17, 2012 at 18:25
  • It works better with "MM/dd/yyyy" as format. Commented Aug 17, 2012 at 18:55
  • @Henk Could you please give me a working example, not just suggestions because I have seen a lot and I could not get it work. Commented Aug 17, 2012 at 18:59

2 Answers 2

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;
//                                                                ^^^^^^^^^^^^^^^^^
Sign up to request clarification or add additional context in comments.

1 Comment

Your last line of code gives me this error: Error CS0029 Cannot implicitly convert type 'string' to 'System.IFormatProvider'
1

This works fine for me:

DateTime date = 
DateTime.ParseExact("20122018", "dd/MM/yyyy", 
                   CultureInfo.CurrentCulture);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.