I am working on a mobile app using ionic framework. I have created a common Utility services like this
.service('CommonUtilityService', function($q) {
return {
parseJsonDate:function(jsonDate){
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined)
parts[2] = 0;
if (parts[3] == undefined)
parts[3] = 0;
return new Date(+parts[1] + offset + parts[2]*3600000 + parts[3]*60000);
},
daysBetween:function(date1String, date2String){
var ONE_DAY = 1000 * 60 * 60 * 24;
var ONE_MINUTE = 1000 * 60;
var d1 = new Date(date1String);
var d2 = new Date(date2String);
var d1_ms = d1.getTime() - d1.getTimezoneOffset() * ONE_MINUTE;
var d2_ms = d2.getTime() - d2.getTimezoneOffset() * ONE_MINUTE;
return Math.floor(d1_ms - d2_ms/ONE_DAY);
},
getNumberOfDays:function(jsonDate){
// var date = parseJsonDate(jsonDate);
var date = new Date();
var today = new Date();
return this.daysBetween(today,date);
}
}
})
When I am trying to call daysBetween function inside getNumberOfDays function it is giving error
this.daysBetween is not a function
Can anyone tell me how can I call daysBetween function inside getNumberOfDays function.
Actually Service doesn't return a object where Factory return an object. You could try refactored service like this
Service
A service is a constructor function which creates the object using the new keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains method).
Code
.service('CommonUtilityService', function($q) {
var CommonUtilityService = this;
CommonUtilityService.parseJsonDate = function(jsonDate) {
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined)
parts[2] = 0;
if (parts[3] == undefined)
parts[3] = 0;
return new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
}
CommonUtilityService.daysBetween = function(date1String, date2String) {
var ONE_DAY = 1000 * 60 * 60 * 24;
var ONE_MINUTE = 1000 * 60;
var d1 = new Date(date1String);
var d2 = new Date(date2String);
var d1_ms = d1.getTime() - d1.getTimezoneOffset() * ONE_MINUTE;
var d2_ms = d2.getTime() - d2.getTimezoneOffset() * ONE_MINUTE;
return Math.floor(d1_ms - d2_ms / ONE_DAY);
}
CommonUtilityService.getNumberOfDays = function(jsonDate) {
// var date = parseJsonDate(jsonDate);
var date = new Date();
var today = new Date();
return CommonUtilityService.daysBetween(today, date);
}
})