Conversion to Time 12 hour Format From String containing Time in 24 hour format

c#, sql, sql-server

Solution

You can do something like this:

string input = "22:45";

var timeFromInput = DateTime.ParseExact(input, "H:m", null, DateTimeStyles.None);

string timeIn12HourFormatForDisplay = timeFromInput.ToString(
    "hh:mm:ss tt", 
    CultureInfo.InvariantCulture);

var timeInTodayDate = DateTime.Today.Add(timeFromInput.TimeOfDay);

And now the important parts to take in consideration:

- The format for parsing uses `"H:m"` so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;

- The format for printing uses `"hh:mm:ss tt"` because it seems to be the format you desire, however you need to use `CultureInfo.InvariantCulture` to be certain that you get a AM/PM designator that is in fact AM or PM. If you use another culture, the AM/PM designator may change;

- The full date and time is constructed based on `DateTime.Today` which returns the today date with a zeroed time and then we just add the time we read from input.

To create the final date and time from another date you can instead use:

var timeInAnotherDate = new DateTime(2000, 1, 1).Add(timeFromInput.TimeOfDay);

Reference material:

- DateTime Structure;

- Custom Date and Time Format Strings;

- Standard DateTime Format Strings.

Problem

I have a `varchar(5)` column in a table which contains the hour and minutes in 24 hour format time. I want to convert this 24 hour format to 12 hour format and finally embed this 12 hour format time into a DateTime Variable along with a Date value. Below is an example of demonstration. For Example 8:18 should be converted into 8:18:00 AM and then should be embedded with a Date like 8/10/2012 8:18:50 AM to be able to store in DateTime column of DB. ``` 22:20......10:20:00 PM.......8/10/2012 10:20:00 PM ``` The Date will not be current date it can be any date value like 8/8/2012 or 7/8/2012

Original source