8

I need to calculate the number of weeks difference between the chosen date and the current date. I've tried to calculate with weekNumberPicked - weekNumberCurrent, but if the two dates are in different years, the result is incorrect, so I probably need to get it like daysDifference / 7. How should I implement this with the onSelect action?

nickf
  • 537,072
  • 198
  • 649
  • 721
Petya petrov
  • 2,153
  • 5
  • 23
  • 35

3 Answers3

20

You can use the Datepicker's function getDate to get a Date object.

Then just subtract one date from the other (might want to get the absolute value as well) to get the milliseconds in difference, and calculate the difference in days, or weeks.

$('#test').datepicker({
    onSelect: function() {
        var date = $(this).datepicker('getDate');
        var today = new Date();
        var dayDiff = Math.ceil((today - date) / (1000 * 60 * 60 * 24));
    }
});
Andy Ford
  • 8,410
  • 3
  • 26
  • 36
Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
2

Since DatePicker getDate() methode returns a javascript Date object, you can do something like :

var myDate = $('.datepicker').datepicker('getDate');
var current = new Date();
var difference = myDate - current;

difference now contains the number of milliseconds between your two dates , you can easily compute the number of weeks :

var weeks = difference / 1000 / 60 / 60 / 24 / 7;
krtek
  • 26,334
  • 5
  • 56
  • 84
0

try this code and applied it to your work :D

$("#date_born").datepicker({
    onSelect: function () {
        var start = $('#date_born').datepicker('getDate');
        var end   = new Date();
        var age_year   = Math.floor((end - start)/31536000000);
        var age_month   = Math.floor(((end - start)% 31536000000)/2628000000);
        var age_day   = Math.floor((((end - start)% 31536000000) % 2628000000)/86400000);
        $('#age').val(age_year +' year ' + age_month + ' month ' + age_day + ' day');
    },
    dateFormat: 'dd/mm/yy',
    maxDate: '+0d',     
    yearRange: '1914:2014',
    buttonImageOnly: false,
    changeMonth: true,
    changeYear: true
});

Html Code:

Date <input type="text" name="date_born" id="date_born"/> 
Age <input type="text" name="age"  id="age" />
Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
ZooboMe23
  • 23
  • 2