Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

theUnforgiven's avatar

Flatpickr and calculate date lengths

Hi all,

I have a couple of inputs, one uses Flatpickr to select a date, and then the other has a list of tenancy lengths, ranging from 6 months to 5 years.

I want to know how I can calculate the length of these to show when the end date will be? So based on the screenshot, that should show as 24th August 2020, this is what I need to calculate and then show.

0 likes
2 replies
theUnforgiven's avatar

This is what I had in jquery:

function updateEndDate() {
        var dates = $startDate.selectedDates;

        if (dates.length === 0) {
            return false;
        }

        var duration = $('#duration').val();
        var startDate = moment(dates[0]);
        var endDate = null;

        if (duration.length > 0 && startDate.isValid()) {
            durationInt = duration.replace(/\D/g,'');
            durationKey = duration.includes('years') ? 'y' : 'M';
            endDate = startDate.add(durationInt, durationKey).subtract(1, "days");

            $('#end-date .date').text(endDate.format('Do MMMM YYYY')).parent().fadeIn();
        } else {
            $('#end-date .date').empty();
        }
    }

    var $startDate = $("#start_date").flatpickr({
        dateFormat: 'J F Y',
        onChange: function (selectedDates, dateStr, instance) {
            return updateEndDate();
        }
    });

But I'm moving away from jQuery and want to replicate this working in Vue instead

theUnforgiven's avatar
theUnforgiven
OP
Best Answer
Level 51

Actually managed to just replicate

 updateEndDate() {
                var dates = this.form.start_date.selectedDates;
                var duration = this.form.duration;
                var startDate = moment(dates);
                var endDate = null;

                if (duration.length > 0 && startDate.isValid()) {
                    let durationInt = duration.replace(/\D/g,'');
                    let durationKey = duration.includes('years') ? 'y' : 'M';
                    endDate = startDate.add(durationInt, durationKey).subtract(1, "days");
                    
                    this.endDate = endDate.format('Do MMMM YYYY');
                } else {
                    this.endDate = '';
                }
            }

Useful for anyone else and my future self ;)

Please or to participate in this conversation.