简体   繁体   中英

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.

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM