Search code examples
javascriptc#timespantime-format

Whole and fractional hours Double value convert to 12-hour Clock Format time


In my MongoDB Database, there is collection called BusSchedule with the following fields

BusSchedule

  • -Double StartTime --> contains whole and fractional hours
  • -Double EndTime --> contains whole and fractional hours
  • -String 12hourFormatStartTime
  • -String 12hourFormatEndTime

Here are some typical values that might exist

StartTime = 6.5 --> contains whole and fractional hours 
EndTime = 9.5 --> contains whole and fractional hours 
12hourFormatStartTime = "06:30 AM"
12hourFormatEndTime = "09:30 AM"

StartTime = 8.5 --> contains whole and fractional hours 
EndTime = 14.25 --> contains whole and fractional hours 
12hourFormatStartTime = "08:30 AM"
12hourFormatEndTime = "02:15 PM"

I was wondering if Microsoft had some kind of existing library that could easily convert the Double Data Type representation of whole and fractional hours to the 12-hour Clock Format time.

StartTime = 8.5  -------translated to-----> 12hourFormatStartTime = "08:30 AM"
EndTime = 14.25  -------translated to-----> 12hourFormatEndTime = "02:15 PM"

StartTime = 6.5 -------translated to-----> 12hourFormatStartTime = "06:30 AM"
EndTime = 9.5 -------translated to-----> 12hourFormatEndTime = "09:30 AM"

I'd prefer if I could use C#. I tried to do:

  Double wholeAndFractionalHours = 14.25;
  TimeSpan.FromHours(wholeAndFractionalHours).ToString(@"hh:mm tt"))

But it throws an System.FormatException "Input string was not in a correct format."

I don't want to waste time writing code to do the aforementioned translation. Could someone please tell me if Microsoft or some 3rd-party open source library will handle the aforementioned requirement?

Thanks @Edin:

Here is what I ultimately ended up coding:

 Double wholeAndFractionalHours = 14.25;
 String timeIn12hourClockFormat = (new DateTime().AddHours(wholeAndFractionalHours)).ToString("h:mm tt", CultureInfo.InvariantCulture);

Solution

  • You could create new DateTime:

    var dateTime = new DateTime().AddHours(6.5);
    

    And then use ToString or ToShortTimeString to format the time:

    string time = dateTime.ToShortTimeString();
    

    Or if you explicitly want 12h format with AM/PM:

    string ampm = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);