user1783170
user1783170

Reputation: 113

Convert string into mm/dd/yyyy format

I have following strings in different formats:

16/05/2014
21-Jun-2014
2014-05-16
16-05-2014
5/19/2014
14 May 2014

I need to convert all the above strings into mm/dd/yyyy format in c#. I have tried used DateTime.ParseExact as DateTime dt = DateTime.ParseExact("16-05-2014", "mm/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture) in C# but i am getting the exception as "String was not recognized as a valid DateTime".

I have also tried to use to Convert.ToDateTime() but it is also not working.

Is there any method or function that we can write/available in C# that would convert the above string formats into a single date format i.e into "mm/dd/yyyy" format ??

Any help on this would be greatly appreciated.

Upvotes: 2

Views: 20842

Answers (5)

hunch_hunch
hunch_hunch

Reputation: 2331

On a DateTime object you can call .ToString("MM/dd/yyyy"). Given the strings you have, you can first create new DateTime objects for each string and then call .ToString("MM/dd/yyyy"). For example:

var dateAsMmDdYyyy = DateTime.Now.ToString("MM/dd/yyyy");

Upvotes: 0

sr28
sr28

Reputation: 5106

You might find the following method useful to accept whatever date format you want and convert it to DateTime:

public DateTime? DTNullable(string DateTimestring, string CurrDateTimeFormat)
{
    if (string.IsNullOrEmpty(DateTimestring)) return null;
    else
    {
        DateTime datetimeNotNull;
        DateTime.TryParseExact(DateTimestring, CurrDateTimeFormat, null, System.Globalization.DateTimeStyles.None, out datetimeNotNull);
        return datetimeNotNull;
    }
}

Pass in your desired string to be converted to DateTime along with it's current date time format and this would return you a nullable DateTime. If you're certain that whatever string you're passing in won't be null then you can remove that bit. The reason for it being there is that you can't convert a null to DateTime. In my case I couldn't be certain if it would be or not so I needed the ability to capture nulls as well.

You can use it like this:

DateTime? MyDateTime = DTNullable(MyStartDate, "dd/MM/yyyy");

If you wanted you could alter the method to accept an array of strings and simply iterate through each and return them all in a list if they were of the same format.

As others have pointed out, months are MM not mm (minutes).

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415820

It fails on the very first term of your format string, which is telling the function to treat the "16" as minutes and to look for hours, minutes, and seconds that don't exist in the input.

You have several different date formats, and so need the ParseExact() overload that accepts several different format strings:

string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd", 
                   "dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};
string converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");

Also remember that lower case "m"s are for minutes. If you want months, you need an upper case "M". Full documentation on format strings is here:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Finally, I suspect you are getting ahead of yourself on formatting the output as a string. Keep these values as DateTime objects for as long as possible, and only format to a string at the last possible moment before showing them to the user. If you really do want a string, at least stick with the ISO 8601 standard format.

Upvotes: 3

DGibbs
DGibbs

Reputation: 14618

Few things:

Your input date 16/05/2014 doesn't match your format Month/Day/Year - how can there be a 16th month?

Secondly, you're using mm which represents Minutes, not Months. You should use MM.

Finally, your sample string 16-05-2014 doesn't match the format provided, you've used hyphens - instead of forward slashes /

Supply a collection of different formats matching your input:

string[] formats = new [] { "MM/dd/yyyy", "dd-MMM-yyyy", 
                            "yyyy-MM-dd", "dd-MM-yyyy", "dd MMM yyyy" };
DateTime dt = DateTime.ParseExact("05-16-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None);

Upvotes: 0

Obl Tobl
Obl Tobl

Reputation: 5684

Your main problem is that your format string is wrong. A small m is for minute, a big M is for month.
Try to pass all your formats in an array. For example like this

DateTime.ParseExact("16-05-2014",
                    new[] {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd", 
                        "dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"},
                    CultureInfo.InvariantCulture, DateTimeStyles.None);

With this you can parse all your formats at once. For more information about the format settings, see the official docs.

Upvotes: 1

Related Questions