0

I have here a javascript function in some view. The controller send to this view two dates(start_date & end_date). All i want to do in my function is to check a condition before doing some action.

<script>
$(function() {
  var start_date = <% @date1 %>
  var end_date = <% @date2 %>
  unavailableDates = [];
  $.ajax({
    url: '/preload',
    data: {'voiture_id': <%= @voiture.id %>},
    dataType: 'json',
    success: function(data) {
      $.each(data, function(arrID, arrValue) {
        for(var d = new Date(arrValue.start_date); d <= new Date(arrValue.end_date); d.setDate(d.getDate() + 1)) {
          // CHECK that !(d >= start_date && d <= end_date) before push action
          unavailableDates.push($.datepicker.formatDate('d-m-yy', d));
        }
      });
}
</script> 

. Types of start_date & end_date

    t.datetime "start_date"
    t.datetime "end_date"

I hope that it was clear, thanks !

SOLUTION:

    var startDate = new Date(<%= @date1.to_i*1000 %>);
    var endDate = new Date(<%= @date2.to_i*1000 %>); 

.

                    if (!(d.getDate()>=startDate.getDate() && d.getDate()<=endDate.getDate()))
                {  
                unavailableDates.push($.datepicker.formatDate('d-m-yy', d));       
                }

1 Answers1

0

Here is the code snippet which performs the same functionality that you are trying to achieve. Looks like you are missing getTime() function during evaluating the date.

/* setting up temporary date range for iteration */

var unavailableDates = [];
var endDate=new Date();
var startDate=new Date(endDate);
startDate.setDate(startDate.getDate()-7);

for(var startdt= new Date(startDate);
    startdt.getTime()<endDate.getTime();
    startdt.setDate(startdt.getDate()+1)){

  if(startdt.getTime()>=startDate.getTime() && startdt<=endDate.getTime())
  {         
      unavailableDates.push(new Date(startdt));
  }    
}
sameer
  • 1,635
  • 3
  • 23
  • 35
  • Thanks @sameer, but i don't see the purpose of using a loop, beside it increases the complexity ! – Amine Bakori Jun 16 '16 at 19:24
  • @Amine have taken the same logic as ur code i.e. for(var d = new Date(arrValue.start_date); d <= new Date(arrValue.end_date); d.setDate(d.getDate() + 1)) , it is up to you whether ur business logic needs it or not, Have showed you the logic of comparing the dates adopting ur logic. However, if you requirement is different then you have to explain the requirement with more details. – sameer Jun 17 '16 at 05:20
  • I found out the solution, it was all about this: new Date(<%= @date1.to_i*1000 %>); Thanks anyway ! – Amine Bakori Jun 18 '16 at 02:32