java间日期大小比较的方法分享
下文笔者讲述java代码对日期大小比较的方法分享,如下所示
3.转换date格式换成秒数比较秒数大小
实现思路:
Date对象中before()和after()方法
转换为time比较
例:
1.使用Date自带方法before()方法和after()方法
String start = new String("2023-03-14 14:23:20");
String end=new String("2023-03-14 14:03:20");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = sdf.parse(start);
Date endDate = sdf.parse(end);
boolean r1=startDate.before(endDate);
boolean r2=startDate.after(endDate);
System.out.println(r1);
System.out.println(r2);
} catch (ParseException e) {
e.printStackTrace();
}
2.使用String的companyTo()方法
String start = new String("2023-03-14 14:23:20");
String end=new String("2023-03-14 14:03:20");
int i = start.compareTo(end);
System.out.println(i);
//值相等返回0
//前者小于后者返回负数
//前者大于后者返回正数。
3.转换date格式换成秒数比较秒数大小
getTime()方法
String start = new String("2023-03-14 14:23:20");
String end=new String("2023-03-14 14:03:20");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = sdf.parse(start);
Date endDate = sdf.parse(end);
long t1 = startDate.getTime();
long t2 = endDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


