Find the closest time from a list of times

后端 未结 11 801
眼角桃花
眼角桃花 2020-12-02 23:48

So, here\'s the scenario. I have a file with a created time, and I want to choose a time from a list of times that that file\'s created time is closest or equal too...what w

11条回答
  •  自闭症患者
    2020-12-03 00:12

    I thought I would update this post to include a real world scenario. I wanted this sort of function as I have a blog showing news of the latest movie screenings.

    However I don't want to list screening in the past (ie screening date past the current date) and as I wanted to show a record I needed some sort of ID passed to pick up the record.

    I have left if simple so that you can follow the process and no doubt make it more efficient with LINQ et al.

    First the model

            public class LatestScreeeningsModel
        {
            public int Id { get; set; }
            public DateTime Date { get; set; }
        }
    

    Then the code block you can call from your controller

            private static LatestScreeeningsModel GetLatestScreening(IPublishedContent currentNode)
        {
            LatestScreeeningsModel latestScreening = new LatestScreeeningsModel();
    
            DateTime fileDate;
    
            // get a list of screenings that have not shown yet
            var screenings = currentNode.AncestorsOrSelf("siteLanguage")
                                       .FirstOrDefault().Descendants("screening")
                                       .Select(x => new LatestScreeeningsModel() { Id = x.Id, Date = x.GetPropertyValue("date") })
                                       .Where(x => x.Date > DateTime.Now).ToList();
    
            fileDate = DateTime.Today;
    
            long min = Math.Abs(fileDate.Ticks - screenings[0].Date.Ticks);
            long diff;
            foreach (var comingDate in screenings)
            {
                diff = Math.Abs(fileDate.Ticks - comingDate.Date.Ticks);
                if (diff <= min)
                {
                    min = diff;
                    latestScreening = comingDate;
                }
            }
    
            return latestScreening;
    
        }
    

    I am using Umbraco to get the date items but it would work with any custom model, List et al.

    Hope it helps

提交回复
热议问题