Possible Duplicate:
How to convert Milliseconds to “X mins, x seconds” in Java?
Calculating the Difference Between Two Java Date Instances
我有这样的功能:
public String setDateAndTime(int h, int m, int s,int amPm) {
TimeZone nst = TimeZone.getTimeZone("GMT+5:45");
Calendar calendar1 = new GregorianCalendar(nst);
Date currentTime1 = new Date();
calendar1.setTime(currentTime1);
calendar1.set(Calendar.HOUR, h);
calendar1.set(Calendar.MINUTE, m);
calendar1.set(Calendar.SECOND, s);
calendar1.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH));
calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH));
calendar1.set(Calendar.AM_PM, amPm);
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
String date = formatter.format(calendar1.getTime());
return date;
}
通过此函数,我创建了两个日期(字符串)
String s1=setDateAndTime(12,00,00,1);//12:00:00 PM
String s2=setDateAndTime(3,15,45,0);//3:15:45 AM
现在如何找到s1和s2之间的差异,我还需要小时,分钟和秒数,以便我可以进行进一步处理。
最佳答案
您可以通过调用getTime()
获得以毫秒为单位的时间。然后比较long
值。milliis/1000
给出秒,millis/60/1000
给出分钟,millis/3600/1000
给出小时,依此类推。
您还可以使用JodaTime之类的第三方库,但如果需要一次,Joda太多了。