如何比较Java之间的日期?
例:
date1是22-02-2010
date2,07-04-2010今天
是date325-12-2010
date3总是大于date1而且date2永远是今天.如何验证今天的日期是否在date1和date3之间?
我正在添加这个问题,因为我是Java和Android的新手,我搜索了几个小时试图解决这个问题.答案来自相关答案的组合,所以我想我会记录我为其他可能正在努力的人学到的东西.见答案.
对于一些背景知识,我的经验主要是PHP的Web开发和一点Ruby.我唯一的操作系统是Linux(Ubuntu Studio),我(不情愿地)在Android Studio 2.1.2中开发我的第一个Android应用程序.我的Java设置如下:
>java -version
> openjdk version "1.8.0_91"
> OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-3ubuntu1~15.10.1-b14)
> OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
Run Code Online (Sandbox Code Playgroud) datetime android android-gradle-plugin threetenbp threetenabp
两个日期正在比较,但时间没有正确比较.这是我的代码
final String setdate = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
final String settime = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(5)));
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat formatter1 = new SimpleDateFormat("dd/M/yyyy");
String currentDate = formatter1.format(calendar1.getTime());
Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat formatter2 = new SimpleDateFormat("h:mm");
String currentTime = formatter2.format(calendar2.getTime());
if(currentDate.compareTo(setdate)>=0)
{
if(currentTime.compareTo(settime)>=0) {
myCheckBox.setChecked(true);
myCheckBox.setEnabled(false);
}
}
Run Code Online (Sandbox Code Playgroud)
如何比较两次.在数据库日期和时间字段不同.所以请帮助我.
我的日期类型为“EEE MM DD HH:mm:ss zzz yyyy”(Wed Mar 04 03:34:45 GMT+08:00 2020)和“yyyy-MM-dd hh:mm:ss”(2020-02) -04 02:10:58).如何在java中比较这两个日期?
两个日期都在同一时区。
我给出了一个 LocalDate 值,然后我想给出另一个值,但我想确保新的值与之前的值不同。我写了一些代码,但似乎不起作用。
Flight flight = new Flight();
System.out.println("Give the day of the departure.");
LocalDate day = LocalDate.of(2019, Month.MAY, scanner.nextInt());
flight.setDateOfDeparture(day);
boolean theDay = true; //Flag (reversed way in order to achieve the TRUE logic value).
for (Flight flight1 : flightList) {
if (flight1.getDateOfDeparture() == (flight.getDateOfDeparture())) {
theDay = false;
}
}
if (theDay) {
// Some logic...
}
Run Code Online (Sandbox Code Playgroud)
我也尝试了关键字 equals 。但 for 循环再次忽略比较。
for (Flight flight1 : flightList) {
if (flight1.getDateOfDeparture().equals(flight.getDateOfDeparture())) {
theDay = false;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的回答之后,我尝试了您提出的许多解决方案。为了检查编译器是否进入 for …
我有两个日期时间字符串,一个是当前时间,第二个如下所示。
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Run Code Online (Sandbox Code Playgroud)
现在我想检查是否endTime已经通过currentTime。
谢谢
java ×5
android ×3
datetime ×3
comparison ×1
date ×1
localdate ×1
threetenabp ×1
threetenbp ×1