I want to subtract two timeperiods say 16:00:00 from 19:00:00. Is there any java function for this? The results can be in milliseconds, seconds, or minutes.
class TimeCalculator { String updateTime;
public TimeCalculator(String time)
{
// time should be in 24 hours format like 15/06/2016 17:39:20
this.updateTime = time;
}
public String getTimeDifference()
{
String td=null;
// get Current Time
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date currentDate = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(currentDate);
int c_year = calendar.get(Calendar.YEAR);
int c_month = calendar.get(Calendar.MONTH) + 1;
int c_day = calendar.get(Calendar.DAY_OF_MONTH);
// get Editing Time
Date edit_date = sdf.parse(updateTime);
Calendar edit_calendar = new GregorianCalendar();
edit_calendar.setTime(edit_date);
int e_year = edit_calendar.get(Calendar.YEAR);
int e_month = edit_calendar.get(Calendar.MONTH) + 1;
int e_day = edit_calendar.get(Calendar.DAY_OF_MONTH);
if(e_year==c_year&&e_month==c_month&&e_day==c_day)
{
int c_hours = calendar.get(Calendar.HOUR_OF_DAY);
int c_minutes = calendar.get(Calendar.MINUTE);
int c_seconds = calendar.get(Calendar.SECOND);
int e_hours = edit_calendar.get(Calendar.HOUR_OF_DAY);
int e_minutes = edit_calendar.get(Calendar.MINUTE);
int e_seconds = edit_calendar.get(Calendar.SECOND);
if(c_hours==e_hours&&c_minutes==e_minutes&&c_seconds==e_seconds)
{
td = "just now";
return td;
}
else if(c_hours==e_hours&&c_minutes==e_minutes)
{
int d_seconds = c_seconds-e_seconds;
td = String.valueOf(d_seconds);
td = td+" seconds ago";
return td;
}
else if(c_hours==e_hours&&c_minutes!=e_minutes)
{
int d_minutes = c_minutes-e_minutes;
int d_seconds;
if(c_seconds>e_seconds)
{
d_seconds = c_seconds-e_seconds;
}else{
d_seconds = e_seconds-c_seconds;
}
td = "00:"+String.valueOf(d_minutes)+":"+String.valueOf(d_seconds)+" ago";
return td;
}
else
{
int d_minutes,d_seconds,d_hours;
d_hours=c_hours-e_hours;
if(c_minutes>e_minutes)
{
d_minutes = c_minutes-e_minutes;
}else{
d_minutes = e_minutes-c_minutes;
}
if(c_seconds>e_seconds)
{
d_seconds = c_seconds-e_seconds;
}else{
d_seconds = e_seconds-c_seconds;
}
td = String.valueOf(d_hours)+":"+String.valueOf(d_minutes)+":"+String.valueOf(d_seconds)+" ago";
return td;
}
}
else if(e_year==c_year&&e_month==c_month&&c_day==e_day+1){
td = "yesterday";
return td;
}
else{
td = updateTime;
return td;
}
}}