• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 273
  • Last Modified:

what is a safe method of formatting dates to such as dd/mm/yyyy in C#

I am relatively new to C#. been googling about this but see no good way of doing what I want.
i want to convert any type of date to dd/mm/yyyy ( or dd-mm-yyyy for that matter ).
The string I want to convert can be in ay valid date format such as

Thanks very much.
4 Solutions
Before you convert it, you need to know what format you use for input. Often, when you "just" use DateTime.Parse it will go correct (use .TryParse to find out whether it is parsable at all and prevent an error). You cannot reasonably expect to know beforehand that a date like 03/05/2006 is 03 May or 05 March. If you cannot know that, the computer cannot either.

Can you update with how we can determine what format to use from the three possibilities above? How do you define "any" date format, because there are literally thousands and thousands of date formats in the world....
Date and Time representations are - in all MS language versions - coupled to the 'LOCALE' that the computer is in. In programs written for the international market it is a given that the date/time shown by a program will be that which the person using the machine is used to. Taking proper care with the 'LOCALE' makes this mostly fully automatic.
The keywords Locale and CultureInfo in MSDN should lead you in the right direction.

If you use the CultureInfo then you can not say that every Date string is appropriate for the conversion, because only valid dates - according to the specific culture - are acceptable.
If you do not use the culture info - then you can not parse every valid string date, because you don't know how to distignuish between dates.
For example: if you get 11/12/2008. you don't know whether the 11 means month and 12 means day, or vice versa.
Since you say you are relatively new to C#, you might not realize that most types have a ToString() method that will create a string representation of the object. So once you have parsed the input string into a DateTime object (as abel explained above) you can just call ToString() to get the newly formatted string. I think there are more options for formatting the string, but that should get you started.
indikadAuthor Commented:
Thank you for all - now I have a good starting point and some very good directions.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now