比较时间大小
getTime()时间戳
将Date类型转换为Long时间戳换算
package com.example.demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCompare {
public static void main(String[] args) throws ParseException {
String startDateStr = "2020-11-17 22:00:00";
String endDateStr = "2020-11-17 21:00:00";
SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddHHmmss");
Date startDate = sim.parse(startDateStr);
Date endDate = sim.parse(endDateStr);
if(startDate.getTime()-endDate.getTime() > 0){
System.out.println("开始时间大于结束时间");
} else if (startDate.getTime()-endDate.getTime() < 0){
System.out.println("开始时间小于结束时间");
} else {
System.out.println("开始时间等于结束时间");
}
}
}
after | before | equals
转时间后计算
package com.example.demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCompare {
public static void main(String[] args) throws ParseException {
String startDateStr = "2020-11-17 09:00:00";
String endDateStr = "2020-11-17 21:00:00";
SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddHHmmss");
Date startDate = sim.parse(startDateStr);
Date endDate = sim.parse(endDateStr);
if(startDate.after(endDate)){
System.out.println("开始时间大于结束时间");
} else if(startDate.before(endDate)) {
System.out.println("开始时间小于结束时间");
} else if(startDate.equals(endDate)) {
System.out.println("开始时间等于结束时间");
}
}
}
compareTo
字符串直接比较
package com.example.demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCompare {
public static void main(String[] args) throws ParseException {
String startDate = "2020-11-17 21:00:00";
String endDate = "2020-11-17 21:00:00";
if(startDate.compareTo(endDate) > 0){
System.out.println("开始时间大于结束时间");
} else if(startDate.compareTo(endDate) < 0) {
System.out.println("开始时间小于结束时间");
} else if(startDate.compareTo(endDate) == 0) {
System.out.println("开始时间等于结束时间");
}
}
}
replaceAll
把字符串类型的日期数据转化成长整型,然后比较大小
package com.example.demo;
public class DateCompare {
public static void main(String[] args) {
String startDateStr = "2020-11-17 22:00:00";
String endDateStr = "2020-11-17 22:00:00";
//使用正则将符号去除
Long startDate = Long.parseLong(startDateStr.replaceAll("\\D",""));
Long endDate = Long.parseLong(endDateStr.replaceAll("\\D",""));
if(startDate > endDate){
System.out.println("开始时间大于结束时间");
} else if(startDate < endDate) {
System.out.println("开始时间小于结束时间");
} else if(startDate.equals(endDate)) {
System.out.println("开始时间等于结束时间");
}
}
}