Ken 99
Ken 99

Reputation: 35

Convert dd/MM/yyyy HH:mm tt to MM/dd/yyyy HH:mm tt in C#

I want to convert string as : "25/12/2017 4:00 PM" to "12/25/2017 4:00 PM". My code :

var TDXRSC = "25/12/2017 4:00 PM";
DateTime.ParseExact(TDXRSC, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture);

But it's not working.

Upvotes: 0

Views: 4072

Answers (4)

SANDHYA RATHORE
SANDHYA RATHORE

Reputation: 1

var TDXRSC = "25/12/2017 4:00 PM";
DateTime date = Convert.ToDateTime(TDXRSC);
string Format = date.ToString("MM/dd/yyyy h:mm tt");

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29026

Hope that .TryParseExtract will be more safe to use for conversion, use like the following:

var dateString = "25/12/2017 4:00 PM";
DateTime inputDate; 
if(DateTime.TryParseExact(dateString, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
{
   var output = inputDate.ToString("MM/dd/yyyy hh:mm tt");
   Console.WriteLine(output);
}
else
{
     Console.WriteLine("Conversion failed");
}

Working Example

Upvotes: 0

Matt Davis
Matt Davis

Reputation: 470

var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
var output = input.ToString("MM/dd/yyyy h:mm tt");

When you call ParseExact you're telling the compiler what format the incoming date is. You can then use ToString() method to provide a format for a string representation of the parsed date.

Upvotes: 0

Nico
Nico

Reputation: 12683

The issue is your date format expected is dd/MM/yyyy hh:mm tt but the reference date only has a single digit hour 4. You are probably better off not expect leading zeros for days, months or hours.

Try..

var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);

This will also still parse 2 digit hours. So var TDXRSC = "25/12/2017 12:00 PM"; will still parse correctly.

Upvotes: 2

Related Questions