DotNetCore/Answer Detail

how to convert 24 hours string format to 12 hours format in c#

Stevan
Stevan
12 Points
6 Posts

how to convert 24 hours string format to 12 hours format in c#?

For examle:

"20:30" to "8:30 pm"

"09:30" to "9:30 am"

Total Answered: 2
Total Marked As Answer: 1
Posted On: 07-Aug-2018 04:08

Share:   fb twitter linkedin
Answers
Smith
Smith
Participant
346 Points
103 Posts
Marked as answer      

Use following extension method to Convert 24 hours format to 12 hours or vice versa.

using System;
using System.Globalization;

namespace NiceOne.Extensions
{
    public static class DateTimeExtentions
    {
        public static string ConvertFromToTime(this string timeHour, string inputFormat, string outputFormat)
        {
            var timeFromInput = DateTime.ParseExact(timeHour, inputFormat, null, DateTimeStyles.None);
            string timeOutput = timeFromInput.ToString(
                outputFormat,
                CultureInfo.InvariantCulture);
            return timeOutput;
        }
    }
}

Examples:

var temp = "13:30";
var temp12hour1 = temp.ConvertFromToTime("HH:mm", "h:mm tt");
var temp12hour2 = temp.ConvertFromToTime("HH:mm", "0h:mm tt");
Posted On: 10-Aug-2018 03:44
great man.
 - Stevan  10-Aug-2018 09:09
mybot
mybot
2 Points
1 Posts
     

Try following code:

string time24 = "20:15";
DateTime dt = DateTime.ParseExact(time24, "HH:mm", null, DateTimeStyles.None);;
String time12 = dt.ToString("HH:mm tt");
Console.Write(militaryDate);
Posted On: 10-Aug-2018 08:20
banner

Blog

Active User (2)

 Log In to Chat