0

我有以下代码,当前给了我一个小时/分钟(24 小时格式)的时间跨度列表。我需要更改 string.format 以显示小时/分钟 AM 或 PM(12 小时格式)。

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();
        }
4

2 回答 2

7
    [Test]
    public void TimeSpan_PmAmFormat()
    {
        TimeSpan timeSpan = new TimeSpan(23, 20, 0);
        DateTime dateTime = DateTime.MinValue.Add(timeSpan);

        CultureInfo cultureInfo = CultureInfo.InvariantCulture;

        // optional
        //CultureInfo cultureInfo = new CultureInfo(CultureInfo.CurrentCulture.Name);
        //cultureInfo.DateTimeFormat.PMDesignator = "PM";

        string result = dateTime.ToString("hh:mm tt", cultureInfo);

        Assert.True(result.StartsWith("11:20 PM"));
    }
于 2013-10-25T16:34:59.987 回答
3

看起来您可以更改代码以IEnumerable<DateTime>非常轻松地返回。

//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));

然后你可以调用ToString()你的DateTime对象: .ToString("hh:mm tt")

于 2013-10-25T16:37:18.923 回答