Question

I have the following code that current gives me a list of timespans with a hour/minute (24-Hour format). I need to change the string.format to show hour/minute AM or PM (12-Hour format).

var availableTimes =
                _appointmentService.GetAvailableHours(date, appointmentId)
                    .Select(x => string.Format("{0:D2}:{1:D2}", x.Hours, x.Minutes));

How is the best way to do this? I don't see anyway with a timespan.

*Here is the GetAvailableHours method that it uses.

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();
        }
Was it helpful?

Solution 2

It looks like you could change your code to return an IEnumerable<DateTime> pretty easily.

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

Then you can call ToString() on your DateTime object: .ToString("hh:mm tt")

OTHER TIPS

    [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"));
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top