下面的程序主要介绍了在JAVA里进行时间比较,获得时间差。例如如果要实现一个功能,30分钟内可以提交,超过30分钟后就不能提交了。则:
计算时间差 **/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String systemTime = sdf .format(new Date()).toString();
将截取到的时间字符串转化为时间格式的字符串 **/
Date begin=sdf.parse(2008-03-28 11:55:30);
Date end = sdf.parse(systemTime); long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒
long day=between/(24*3600);
long hour=between%(24*3600)/3600;
long minute=between%3600/60;
long second=between%60/60;
if((hour==0)&&(day==0)&&(minute<=30)) { /****/} 比如:现在是2004-03-26 13:31:40
过去是:2004-01-02 11:30:24
我现在要获得两个日期差,差的形式为:XX天XX小时XX分XX秒
方法一:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
{
Date d1 = df.parse("2004-03-26 13:31:40");
Date d2 = df.parse("2004-01-02 11:30:24");
long diff = d1.getTime() - d2.getTime();
long days = diff / (1000 * 60 * 60 * 24);
}
catch (Exception e)
{
}
方法二:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date now = df.parse("2004-03-26 13:31:40");
java.util.Date date=df.parse("2004-01-02 11:30:24");
long l=now.getTime()-date.getTime();
long day=l/(24*60*60*1000);
long hour=(l/(60*60*1000)-day*24);
long min=((l/(60*1000))-day*24*60-hour*60);
long s=(l/1000-day*24*60*60-hour*60*60-min*60);
System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
方法三:
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date begin=dfs.parse("2004-01-02 11:30:24");
java.util.Date end = dfs.parse("2004-03-26 13:31:40");
long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒 long day1=between/(24*3600);
long hour1=between%(24*3600)/3600;
long minute1=between%3600/60;
long second1=between%60/60;
System.out.println(""+day1+"天"+hour1+"小时"+minute1+"分"+second1+"秒");
我在这里出个错误,天数不对,仔细检查发现是时间的格式问题
这里dateA,dateB的格式要与yyyy-MM-dd一致!切记!
/**
* 根据两个日期,取得相隔的天数
* 方法名 :
* @param dateA
* @param dateB
* @return
*/
public static int getBetweenDayNumber(String dateA, String dateB) {
long dayNumber = 0;
long DAY = 24L * 60L * 60L * 1000L;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
java.util.Date d1 = df.parse(dateA);
java.util.Date d2 = df.parse(dateB);
dayNumber = (d2.getTime() - d1.getTime()) / DAY;
} catch (Exception e) {
e.printStackTrace();
}
return (int) dayNumber;
}