Search code examples
asp.net-mvc-4razorknockout.jsknockout-mvc

Date comparision on cshtml view


I am using the below code to compare 2 dates on cshtml view with knockout binding.

data-bind="visible: (new Date(appointmentDate) - new Date() < 0) && isStart()"

It is working fine but that is including time as well while comparing. I don't want to include time in comparision only date.


Solution

  • I quick search on google pointed me to Formatting Date in Knockout Template this will allow us to get the date and compare it. Looking like

    data-bind="visible: (
        moment(new Date(appointmentDate)).format('MM/DD/YYYY') - 
        moment(new Date()) < 0) && isStart()"
    

    I didn't try just let me know if works

    Also momento allows you to calculate difference of dates

    var dateB = moment('2014-11-11');
    var dateC = moment('2014-10-11');
    
    console.log('Difference is ', dateB.diff(dateC), 'milliseconds');
    console.log('Difference is ', dateB.diff(dateC, 'days'), 'days');
    console.log('Difference is ', dateB.diff(dateC, 'months'), 'months');
    

    So basically we would do

    data-bind="visible: (
            moment(new Date(appointmentDate)).format('MM/DD/YYYY').diff(new Date().format('MM/DD/YYYY'),'days') < 0) && isStart()"