Pages

Thursday, June 12, 2014

Date/Time difference in Duration Android


public static TimeZone timeZone;

public static String dateDiff(String d){


SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 timeZone = TimeZone.getDefault();

 timeZone = TimeZone.getTimeZone("America/New_York");
format.setTimeZone(timeZone);
String currentDateandTime = format.format(new Date());

 Date dt1 = null;
       Date dt2 = null;
       try {
           dt1 = format.parse(d);
           dt2 = format.parse(currentDateandTime);
       } catch (ParseException e) {
           e.printStackTrace();
       }  
     
       long diff = dt2.getTime() - dt1.getTime();
       long diffSeconds = diff / 1000 % 60;
       long diffMinutes = diff / (60 * 1000) % 60;
       long diffHours = diff / (60 * 60 * 1000);
       long a = diffHours%24;
       int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));

       if(diffInDays>0){
       
        return ""+diffInDays+" day";
       }

       else if(a>0){
     
return ""+a+" hr";
}else  {
return ""+diffMinutes+" min";
}
}

No comments:

Post a Comment