Java中日期或时间大小的比对

来源:互联网 发布:java内部类的调用 编辑:程序博客网 时间:2024/06/06 01:05

有一个字符串的时间,比如"2012-12-31 16:18:36" 与另一个时间做比较,如果前者比后者早,则返回true,否则返回false。

代码示例:

  1. import java.util.*;  
  2. import java.text.ParseException;  
  3. import java.text.SimpleDateFormat;  
  4. class Test  
  5. {  
  6.     public boolean compare(String time1,String time2) throws ParseException  
  7.     {  
  8.         //如果想比较日期则写成"yyyy-MM-dd"就可以了  
  9.         SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
  10.         //将字符串形式的时间转化为Date类型的时间  
  11.         Date a=sdf.parse(time1);  
  12.         Date b=sdf.parse(time2);  
  13.         //Date类的一个方法,如果a早于b返回true,否则返回false  
  14.         if(a.before(b))  
  15.             return true;  
  16.         else  
  17.             return false;  
  18.         /* 
  19.          * 如果你不喜欢用上面这个太流氓的方法,也可以根据将Date转换成毫秒 
  20.         if(a.getTime()-b.getTime()<0) 
  21.             return true; 
  22.         else 
  23.             return false; 
  24.         */  
  25.     }  
  26.     public static void main(String[] args) throws Exception  
  27.     {  
  28.         boolean result=new Test().compare("2012-11-30 16:11:16""2012-11-30 16:18:18");  
  29.         System.out.println(result);  
  30.     }  
  31. }  
结果输出true