1 import org.junit.Test; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 /** 7 * @author DateJunit 8 * @Title: DateJunit 9 * @ProjectName DateJunit 10 * @Description: TODO 11 * @date 2018/8/117:41 12 */ 13 public class DateJunit { 14 @Test 15 public void test(){ 16 try { 17 SimpleDateFormat sdft = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); 18 String comparisonStr= "2018-07-31 20:56:56"; 19 String StrOfComparison= "2018-08-01 18:09:52"; 20 Date comparisonDate = sdft.parse(comparisonStr); 21 Date dateOfComparison = sdft.parse(StrOfComparison); 22 23 //1.使用Date的compareTo()方法,1 大于;0 等于;-1 小于 24 System.out.println(comparisonDate.compareTo(dateOfComparison)); 25 26 //2.使用时间戳直接比较大小 27 System.out.println(comparisonDate.getTime() > dateOfComparison.getTime()); 28 29 //3.使用Date的before()、after()方法 30 //如果前者比后者小返回true,否则为false 31 System.out.println(comparisonDate.before(dateOfComparison)); 32 //如果前者比后者大返回true,否则为false 33 System.out.println(comparisonDate.after(dateOfComparison)); 34 }catch (Exception e){ 35 e.printStackTrace(); 36 } 37 38 } 39 }