package mytest; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class TimeTest { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String currentTime = sdf.format(new Date()); System.out.println(currentTime); //輸出 2018-05-17 Service ss = new Service("2018-5-16"); System.out.println(ss.getTime()); // 輸出 2018-5-16 System.out.println( sdf.parse(ss.getTime()).compareTo(sdf.parse(currentTime)) < 0 ); // 輸出 true System.out.println(ss.getTime().compareTo(currentTime)); //輸出 -5 } } class Service { private String time; public Service(String time) { super(); this.time = time; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
時間是字符串 類型時, 比較大小 先要 轉化成 時間格式 比較。
字符串比較大小的規則:
首先取出兩個字符串的長度,比較較小的長度內,兩者是否相等。
若不相等,則直接返回該位置字符的ASCII碼相減后的值。
若各位置都相等,則將兩個字符串長度的差值返回。
