Copied to clipboard

Flag this post as spam?

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


  • Nathan Rogan 22 posts 203 karma points
    Apr 27, 2020 @ 14:22
    Nathan Rogan
    0

    Compare 2 dates with a fallback if null

    Hi,

    I have a disruption feed which displays disruptions happening now and disruptions happening in the future.

    I have the live feed working like this:

    var liveFiltered = disruptions.Where(x => x.Value<DateTime>("startDateTime") <= DateTime.Now.Date)
        .Where(x => x.Value<DateTime>("endDateTime") >= DateTime.Now.Date);
    

    but we have a few events where theres not an end date so they won't be shown (Ongoing).

    Is there a way of adding a fallback value to the "endDateTime"? I have tried the following:

    var endDate = DateTime.Parse("31/12/3000 12:00:00 AM");
    var liveFiltered = disruptions.Where(x => x.Value<DateTime>("startDateTime") <= DateTime.Now.Date)
        .Where(x => x.Value<DateTime>("endDateTime"), endDate >= DateTime.Now.Date);
    

    But fails. Has anyone got any other suggestions?

    Thanks

  • Malthe Petersen 68 posts 383 karma points c-trib
    Apr 27, 2020 @ 15:18
    Malthe Petersen
    0

    Hi Nathan.

    Instead of hard coding the end date, you could try with DateTime.MaxValue.

    Not sure whether it helps you, but it’s worth a try.

    And the end where should probably look something like:

    .Where(x => x.Value<DateTime>(“endDate”) ?? DateTime.MaxValue >= DateTime.Now)
    

    Or something like that. :-)

    Regards Malthe

  • Alex Skrypnyk 6182 posts 24284 karma points MVP 8x admin c-trib
    Apr 27, 2020 @ 15:26
    Alex Skrypnyk
    0

    Another helper method that can help:

    var liveFiltered = disruptions.Where(x => x.HasValue("endDateTime"));
    

    you can get all disruptions with end date and without.

    Thanks,

    Alex

  • Nathan Rogan 22 posts 203 karma points
    Apr 28, 2020 @ 09:40
    Nathan Rogan
    100

    Hi Malthe & Alex,

    Thanks for your suggestions. Much appreciated.

    Tried the DateTime.MaxValue but got : Operator '??' cannot be applied to operands of type 'DateTime' and 'bool'

    Alex's solution worked but then I could not compare if the end date was greater than today.

    I've added an extra checkbox to say if the event is ongoing and got it working using:

    var liveFiltered = disruptions.Where(x => x.Value<DateTime>("startDateTime") <= DateTime.Now.Date)
        .Where(x => x.Value<DateTime>("endDateTime") >= DateTime.Now.Date || (x.Value<bool>("ongoing") == true));
    

    Cheers

    Nath

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies