计算时间差
程序员文章站
2024-01-24 12:05:34
...
计算两个时间的差值
package date0428; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** *@author tonyJ<br/> *2011-4-28 下午03:58:15 */ public class Test01 { public static void main(String[] args) { System.out.println(countTime("2004-01-02 13:31:40","2004-01-02 11:30:24")); } public static String countTime(String startTime,String endTime){ String desc=null; SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long countTime=0; long day=0; long hour=0; long min=0; long second=0; try { Date startDate=sdf.parse(startTime); Date endDate=sdf.parse(endTime); countTime=startDate.getTime()-endDate.getTime(); day=countTime/(1000*60*60*24); hour=countTime/(1000*60*60)-day*24; min = countTime/(1000*60)-day*24*60-hour*60; second=countTime/1000-day*24*60*60-hour*60*60-min*60; //System.out.println(countTime+"-->"+day+"-->"+hour+"-->"+min+"-->"+second); if(day==0&&hour==0&&min==0&&second!=0){ desc="约"+second+"秒前"; } if(day==0&&hour==0&&min!=0){ desc="约"+min+"分钟前"; } if(day==0&&hour!=0){ desc="约"+hour+"小时前"; } if(day>3){ desc=startTime; } } catch (ParseException e) { e.printStackTrace(); } return desc; } }