PDA

View Full Version : Calculate amount of months and days between dates



kdm
13 Dec 2013, 5:54 AM
I'm looking to calculate the number of months and remaining days between two dates. I have a start date and an end date that a user can select. When selecting the end date I'm calling a VTYPE and this is where I want to make my calculation. For example if a user selects November 1st, 2013 as the start date and December 4th as the end date I would want to see "You selected 1 month and 4 days". Is this possible? I was trying to use the Ext.Date.getElasped function but not sure if this is the right approach.

Form fields:


items: [{
xtype: 'datefield',
fieldLabel: 'Start',
name: 'startDate',
allowBlank: false,
editable: false,
vtype: 'daterange',
vfield: 'start_date'
},{
xtype: 'container',
width: 10
},{
xtype: 'datefield',
fieldLabel: 'End',
name: 'endDate',
allowBlank: false,
disabled: true,
editable: false,
vtype: 'daterange',
vfield: 'end_date'
}


VType:


Ext.apply(Ext.form.field.VTypes, {
daterange: function(val, field) {
var date = field.parseDate(val);

if(!date){
return false;
}

var start = field.up('form').down('datefield[vfield=start_date]');
var end = field.up('form').down('datefield[vfield=end_date]');
var create = field.up('form').down('button[action=create]');
var rangeField = field.up('form').down('[rangeField=date_range_display]');

if(field.vfield){
if(start.value && !end.value){
end.setDisabled(false);
}else if(start.value && end.value && start.value <= end.value){
start.clearInvalid();
end.clearInvalid();
create.setDisabled(false);

// This is where I would like to calculate the number of months/days
var range = Ext.Date.getElapsed(start.value,end.value);
rangeField.html = range;
}
}
if(end.value && (start.value > end.value)){
create.setDisabled(true);
return false;
}
return true;
},

daterangeText: 'Start date must be less than end date'
});

Kevin Jackson
17 Dec 2013, 12:40 PM
getElapsed does the check based on milliseconds. I would think in your test example, I would expect 1 month and 3 days.

What would you expect for Nov 21 start and Dec 3rd? I would think that would be reported in days and then the calculation of days in a month once again need to get added into the mix.

I found this example as a possible way to calculate months.
http://stackoverflow.com/questions/2536379/difference-in-months-between-two-dates-in-javascript

Much depends on what you are trying to report back