David
David

Reputation: 1041

CONVERT MM/DD/YYYY HH:MI:SS AM/PM to DD/MM/YYYY in C#

How can I convert MM/DD/YYYY HH:MI:SS AM/PM into DD/MM/YYYY using C# ?I am using C#2008.

Thanks

Upvotes: 4

Views: 22601

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500225

Use TryParseExact to parse to a DateTime, then ToString with a format string to convert back...

DateTime dt;
if (DateTime.TryParseExact(value, "MM/dd/yyyy hh:mm:ss tt",
                           CultureInfo.InvariantCulture, DateTimeStyles.None,
                           out dt))
{
    string text = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
    // Use text
}
else
{
    // Handle failure
}

Upvotes: 17

yoozer8
yoozer8

Reputation: 7489

If this is a DateTime object, you should be able to just select a different format.

If it is a string, use the following:

public string convert(string date){
    string[] pieces = date.Split("/");
    string day = pieces[1];
    string month = pieces[0];
    string year = pieces[2].split(" ")[0];
    return day + "/" + month + "/" + year;
}

Upvotes: 0

Guffa
Guffa

Reputation: 700262

As the time part is irrelevant, you can truncate that before parsing and re-formatting:

date = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture).ToString("dd'/'MM'/'yyyy");

Edit:

As your comment reveals that you don't want a string as result, you should not format the date into a string, just get the date as a DateTime value:

Datetime dbDate = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture);

Now you can use the DateTime value in your code, wrapping it in a database driver type if needed.

Upvotes: 1

Related Questions