如何在 Java 中比較兩個字串格式的日期?
java.text.SimpleDateFormat 用於將字串格式化為日期,以及將日期格式化為字串。
- 該類的建構函式之一接受一個表示所需日期格式的字串值,並建立SimpleDateFormat 物件。
- 將字串解析/轉換為日期物件,請透過傳遞所需格式的字串來例項化該類。
- 使用 parse() 方法解析日期字串。
- util.Date 類表示特定的時間時間,該類提供多種方法(如 before()、after() 和 equals())來比較兩個日期。
示例
建立字串中的日期物件後,可以使用以下方法之一進行比較,如下所示:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String args[])throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM"); String dateStr1 = "2007-11-25"; String dateStr2 = "1999-9-12"; //Parsing the given String to Date object Date date1 = formatter.parse(dateStr1); Date date2 = formatter.parse(dateStr2); Boolean bool1 = date1.after(date2); Boolean bool2 = date1.before(date2); Boolean bool3 = date1.equals(date2); if(bool1){ System.out.println(dateStr1+" is after "+dateStr2); }else if(bool2){ System.out.println(dateStr1+" is before "+dateStr2); }else if(bool3){ System.out.println(dateStr1+" is equals to "+dateStr2); } } }
輸出
2007-11-25 is after 1999-9-12
LocalDate 類中的 Parse() 方法
LocalDate 類中的 parse() 方法接受表示日期的字串值並返回 LocalDate 物件。
示例
import java.time.LocalDate; public class Test { public static void main(String args[]){ String dateStr1 = "2007-11-25"; String dateStr2 = "1999-9-12"; LocalDate date1 = LocalDate.parse(dateStr1); LocalDate date2 = LocalDate.parse(dateStr1); Boolean bool1 = date1.isAfter(date2); Boolean bool2 = date1.isBefore(date2); Boolean bool3 = date1.isEqual(date2); if(bool1){ System.out.println(dateStr1+" is after "+dateStr2); }else if(bool2){ System.out.println(dateStr1+" is before "+dateStr2); }else if(bool3){ System.out.println(dateStr1+" is equal to "+dateStr2); } } }
輸出
2007-11-25 is equal to 1999-9-12
廣告