Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Jonathan Hartley 8 posts 78 karma points
    Nov 19, 2019 @ 19:24
    Jonathan Hartley
    0

    How do I compare an optional content date to today's date?

    I have an optional end date stored in a content model, and I want to compare it to today's date.

    I want to keep the content item if either: a) The end date is not set; or b) The end date is after today's date.

    How can I do this in an Umbraco 8 view template?

    I've tried various things like the following, but none of them work:

    items = items.Where(x => x.Value("EndDate") == null || String.Compare(Umbraco.Library.FormatDateTime(x.Value("EndDate").ToString(), "yyyy-MM-dd"), DateTime.Today.ToString("yyyy-MM-dd")) >= 0);
    

    Thanks.

  • Paul Griffiths 370 posts 1021 karma points
    Nov 20, 2019 @ 09:19
    Paul Griffiths
    0

    Hi Jonathan,

    Is endDate defined as a string or DateTime type on your content model?

    I'm sure there are ways to compare the string but as far as I understand if it's set as a DateTime i.e. on your documentType then you should be able to do the following:

    // check whether you have a date OR if its set to the min date value - if true we want to add it    
    x => x.Value<DateTime>("EndDate") == null || x => x.Value<DateTime>("EndDate") == DateTime.MinValue
    
    // check whether your end date is set in the future or equals the current day - if true we want to add it
    x => x.Value<DateTime>("EndDate")  >= DateTimeNow
    

    I'm on the train so my syntax may be a little off but with the two together maybe try

    items = items
            .Where((x => x.Value<DateTime>("EndDate") == null || x => x.Value<DateTime>("EndDate") == DateTime.MinValue) 
                     || x => x.Value<DateTime>("EndDate") >= DateTime.Now ))
    

    Basically, if the first check equates to false the right check is still evaluated. if either the left or right check evaluates to TRUE then its added to items.

    Maybe it might be worth splitting it up using if statements first and then condense using LINQ. Get it working then refactor.

    When you are outputting the date value in the view you can call ToString() to format it, loop through the items and call

    item.Value<DateTime>("EndDate").ToString("yyyy-MM-dd")
    

    I hope this helps in some way.

Please Sign in or register to post replies

Write your reply to:

Draft