3

I am new to titanium. I want to find time difference in titanium. Ex 12.00 AM- 12.00 PM should give me 12 hours. But I'm not able to get how to find it in titanium.

I'm trying

function calculatetime(chkintime,chkouttime)
{

var difference = chkintime - chkouttime;

Ti.API.info(':'+difference);

var hoursDifference = Math.floor(difference/1000/60/60); 
difference -= hoursDifference*1000*60*60 

var minutesDifference = Math.floor(difference/1000/60); 
difference -= minutesDifference*1000*60 

 Ti.API.info(':'+hoursDifference);
 Ti.API.info(':'+minutesDifference);

 var time=hoursDifference+':'+minutesDifference;

 return time;

}

It sometimes gives correct answer while sometimes negative values.

here chkintime and chkouttime values are in miliseconds e.g. 1355495784321

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
Aditya
  • 31
  • 3

1 Answers1

2

It's no different from finding a time difference in JavaScript. (In fact, it is finding a time difference in JavaScript.)

Check time difference in Javascript

Past that, a nice way to calculate the number of days between X and Y is to find out the MS difference, then add that time to a set date, like January 1st, 2000. Then you can really easily pull the number of years, months, days, hours, minutes, and seconds. There will be some inaccuracy caused by leap years, but if you're dealing with small period, it doesn't matter at all.

var start = new Date('February, 22, 2011 2:00 PM');
var end = new Date('February, 22, 2011 4:00 PM');
var ms = end - start;
var niceDate = new Date(new Date('January 1, 2000').getTime() + ms);
var years = niceDate.getFullYear() - 2000;
var months = niceDate.getMonth();
var days = niceDate.getDate();
var hours = niceDate.getHours();
var minutes = niceDate.getMinutes();
var seconds = niceDate.getSeconds();

alert(years + ' years,\n'
    + months + ' months,\n'
    + days + ' days,\n'
    + hours + ' hours,\n'
    + minutes + ' min,\n'
    + seconds + ' sec');
Community
  • 1
  • 1
Dawson Toth
  • 5,580
  • 2
  • 22
  • 37
  • "You can lead a horse to water..." Edited the above to show you plainly how to get the difference from 4pm to 2pm. – Dawson Toth Jan 21 '13 at 19:04