-7

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?

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
Pravin
  • 47
  • 8
  • Have you tried anything yet? You should probably parse to a `DateTime` (ignoring the date) in the current format, then reformat to the format you want. – Jon Skeet Sep 25 '15 at 12:19
  • 3
    You want to convert `"10:30AM"` to `"10:30:00 AM"`?? – Tim Schmelter Sep 25 '15 at 12:20
  • [Parsing Date and Time Strings in the .NET Framework](https://msdn.microsoft.com/en-us/library/2h3syy57(v=vs.110).aspx) – Liam Sep 25 '15 at 12:20
  • 4
    This is one of them times where I wished *"this is just plain laziness"* was a close reason – Liam Sep 25 '15 at 12:22
  • yes i want to convert "10:30AM" to "10:30:00 AM" – Pravin Sep 25 '15 at 12:24
  • 1
    possible duplicate of [Converting a String to DateTime](http://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – slavoo Sep 25 '15 at 12:28

2 Answers2

2

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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

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:

  • hh: hour part
  • mm: minute part
  • ss: second part
  • tt: represent AM/PM part
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116