I have a string
10:30AM
I want to convert into
10:30:00 AM
The resulting string should be in time format(HH:MM:SS AM/PM). How do I do this?
I have a string
10:30AM
I want to convert into
10:30:00 AM
The resulting string should be in time format(HH:MM:SS AM/PM). How do I do this?
You want to convert "10:30AM"
to "10:30:00 AM"
? Use DateTime
methods:
string time = "10:30AM";
DateTime dt = DateTime.ParseExact(time, "hh:mmtt", DateTimeFormatInfo.InvariantInfo);
string result = dt.ToString("hh:mm:ss tt", DateTimeFormatInfo.InvariantInfo);
worth reading: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
You can try ParseExact
method to convert a custom string to a DateTime
, then use ToString
method to convert it to your desired string format.
var result = DateTime.ParseExact("10:30AM", "hh:mmtt", CultureInfo.InvariantCulture)
.ToString("hh:mm:ss tt");
//result : "10:30:00 AM"
In the DateTime
formatting you may remember these notes: