刚好做项目的时候,需要判断发布的时间是否在两小时内,在两小时内才有效,就写了一个main,希望对大家有帮助
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 2);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = df.format(calendar.getTime());
<span style="white-space:pre"> </span>System.out.println("两个小时前的时间:" + format);
<span style="white-space:pre"> </span>System.out.println("现在的时间"+new Date());
<span style="white-space:pre"> </span>//判断一个时间是否在两个小时内
<span style="white-space:pre"> </span>String date="2016-6-25 10:23:20";
<span style="white-space:pre"> </span>//1.先获取已知的时间
<span style="white-space:pre"> </span>SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>Date parseStr = sim.parse(date);
<span style="white-space:pre"> </span>long timeStr = parseStr.getTime();//已知时间的毫秒值
<span style="white-space:pre"> </span>Date parse2Before = sim.parse(format);
<span style="white-space:pre"> </span>long time2Before = parse2Before.getTime();//两个小时之前的毫秒值
<span style="white-space:pre"> </span>long timeNew = (new Date()).getTime();//当前时间的毫秒值
<span style="white-space:pre"> </span>//判断传来的时间-当前时间<=0,传来的时间-两个小时前的时间>=0
<span style="white-space:pre"> </span>if((timeStr-timeNew<=0)&&(timeStr-time2Before)>=0) {
<span style="white-space:pre"> </span>System.out.println("在两小时之内~~~~啦啦啦啦");
<span style="white-space:pre"> </span>}else {
<span style="white-space:pre"> </span>System.out.println("不在两小时之内~~~~lalalalala");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>} catch (ParseException e) {
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>}
}