整数和小数小时 Double 值转换为 12 小时制时钟格式时间

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

在我的 MongoDB 数据库中,有一个名为 BusSchedule 的集合,其中包含以下字段

公交时刻表

以下是一些可能存在的典型值

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"

我想知道 Microsoft 是否有某种现有的库可以轻松地将整数和小数小时的双精度数据类型表示转换为 12 小时时钟格式时间。

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"

我更愿意使用 C#。我尝试这样做:

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

但是它抛出一个 System.FormatException "Input string was not in a correct format."

我不想浪费时间编写代码来进行上述翻译。有人可以告诉我 Microsoft 或某些第 3 方开源库是否可以满足上述要求吗?

感谢@Edin:

这是我最终完成的编码:

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

您可以创建新的日期时间:

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

然后用ToStringToShortTimeString格式化时间:

string time = dateTime.ToShortTimeString();

或者,如果您明确想要使用 AM/PM 的 12h 格式:

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