C# 使用AM/PM将string.format和timespan转换为12小时格式
我有以下代码,current为我提供了一个小时/分钟24小时格式的时间跨度列表。我需要将string.format更改为显示小时/分钟AM或PM 12小时格式C# 使用AM/PM将string.format和timespan转换为12小时格式,c#,asp.net-mvc-4,timespan,C#,Asp.net Mvc 4,Timespan,我有以下代码,current为我提供了一个小时/分钟24小时格式的时间跨度列表。我需要将string.format更改为显示小时/分钟AM或PM 12小时格式 var availableTimes = _appointmentService.GetAvailableHours(date, appointmentId) .Select(x => string.Format("{0:D2}:{1:D2}", x.Hours
var availableTimes =
_appointmentService.GetAvailableHours(date, appointmentId)
.Select(x => string.Format("{0:D2}:{1:D2}", x.Hours, x.Minutes));
最好的方法是什么?我看不出时间跨度有多大
*下面是它使用的GetAvailableHours方法
public IEnumerable<TimeSpan> GetAvailableHours(DateTime? date, int? appointmentId)
{
if (date == null) return null;
var hours = new List<DateTime>();
for (var ts = new TimeSpan(); ts <= new TimeSpan(23, 30, 0); ts = ts.Add(new TimeSpan(0, 30, 0)))
{
hours.Add(date.Value + ts);
}
var booked = _appointmentRepository.Get
.Where(x =>
(!appointmentId.HasValue || x.Id != appointmentId))
.Select(x => x.ScheduledTime).ToList();
//return available hours from shifts
var workingHours = from h in hours
from s in
_scheduleRepository.Get.Where(
x => x.ShiftStart <= h && x.ShiftEnd >= EntityFunctions.AddHours(h, 1))
where
s.ShiftStart <= h && s.ShiftEnd >= h.AddHours(-1) &&
booked.Count(x => x == h) == 0
select h.TimeOfDay;
//match available hours with another appointment
return workingHours.Distinct();
}
看起来您可以很容易地更改代码以返回IEnumerable
//Get your distinct time spans
var distinctTimeSpans = workingHours.Distinct();
//Build date objects from the parameter and time span objects
var dates = distinctTimeSpans.Select(ts => new DateTime(date.Value.Year, date.Value.Month, date.Value.Day, ts.Hours, ts.Minutes, ts.Seconds));
然后,您可以调用DateTime对象上的ToString:.ToString:mm tt但是如果小时数超过24小时呢?时间跨度可能吗?当然可以。尝试此TimeSpan.FromHours100;。将AM或PM与TimeSpan关联是没有意义的。从TimeSpan对象切换到DateTime可能更有意义。该方法仅假设返回当天在班次开始和结束之间没有预约的可用小时数。所以也许timespan不是这里使用的最好的方法?好吧,我把方法改了,除了改变不同的调用不确定如何使用。@Delriousdev-我编辑了我的答案。我还没有测试代码,但是,我的想法是:构建你独特的时间跨度列表,然后从中构建你的日期时间列表。
//Get your distinct time spans
var distinctTimeSpans = workingHours.Distinct();
//Build date objects from the parameter and time span objects
var dates = distinctTimeSpans.Select(ts => new DateTime(date.Value.Year, date.Value.Month, date.Value.Day, ts.Hours, ts.Minutes, ts.Seconds));