Java 时间戳进行比较

Java 时间戳进行比较

Date

SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);//设置日期格式
String nowDate = df.format(new Date());// new Date()为获取当前系统时间

    String strtime = "1491010346";
    long ltt = new Long(strtime);
    Date datee = new Date(ltt);
    String ress = simpleDateFormat.format(datee);
    try {
        datee = simpleDateFormat.parse(ress);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String time = "1497663146";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    long lt = new Long(time);
    Date date = new Date(lt);
    String res = simpleDateFormat.format(date);
    try {
        date = simpleDateFormat.parse(res);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
if(date.getTime() < datee.getTime()){
    //表示时间date小于时间datee
    system.out.println("date);
}else{
    //表示时间date大于时间datee
    system.out.println("date>datee");
}

时间相差的天数

 1  public static int daysBetween(String smdate,String bdate){  
 2          SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
 3          Calendar cal = Calendar.getInstance();    
 4          long time1 = 0;
 5          long time2 = 0;
 6          
 7          try{
 8               cal.setTime(sdf.parse(smdate));   
 9               time1 = cal.getTimeInMillis();    
10               cal.setTime(sdf.parse(bdate)); 
11               time2 = cal.getTimeInMillis();  
12          }catch(Exception e){
13              e.printStackTrace();
14          }
15          long between_days=(time2-time1)/(1000*3600*24);  
16              
17         return Integer.parseInt(String.valueOf(between_days));     
18      }  

时间相差的小时

 1  public static int daysBetween2(String startTime, String endTime) {
 2           SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH");  
 3           Calendar cal = Calendar.getInstance();    
 4           long time1 = 0;
 5           long time2 = 0;
 6           
 7           try{
 8                cal.setTime(sdf.parse(startTime));   
 9                time1 = cal.getTimeInMillis();    
10                cal.setTime(sdf.parse(endTime)); 
11                time2 = cal.getTimeInMillis();  
12           }catch(Exception e){
13               e.printStackTrace();
14           }
15           long between_days=(time2-time1)/(1000*3600);  
16               
17          return Integer.parseInt(String.valueOf(between_days));     
18       }

你可能感兴趣的:(date)