Calculate number of days between 2 dates and use it as quantity to be added to cart

I am not sure if this is possible or if someone can help with us. I currently have 2 calendars on a product page. And I am calculating the difference between the two dates. But I don’t know how to dynamically display the days difference upon input of the two dates, and to use it as the quantity to be brought into cart.

I am editing the main-product.liquid page and putting the following snippet underneath so that it goes within the same div as the quantity selector.

This is what I have so far:


    

      {{ 'Drop-off Date*' }}
    

    
  

  
    

      {{ 'Pick-up Date*' }}
    

    
  

           

{% assign date_start = 'properties[Dropoff Date]' | date: '%s' %}
{% assign date_end = 'properties[Pickup Date]' | date: '%s' %}

{% assign diff_seconds = date_end | minus: date_start %}

{% assign diff_days = diff_seconds | divided_by: 3600 | divided_by: 24 %}

I would be forever grateful to whoever that can help me solve this.

Hi @nyctibius ,

You need to use JavaScript to achieve what you want.

Code sample:

document.getElementById('calenderinput2').addEventListener('change', function() {
    const startDate = new Date(document.getElementById('calenderinput1').value);
    const endDate = new Date(this.value);

    const diffTime = Math.abs(endDate - startDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 

    // Update quantity field
    document.getElementById('quantity').value = diffDays;
});

If you need assistance implementing this code or customizing it further for your store, feel free to reach out! I offer professional development services and would be happy to help you get this set up. You can contact me directly to discuss your needs and get a quote.