Ton*_*yGW 2 java date java.util.date java-time
我需要检查,如果给定的日期在当月,和我写了下面的代码,但IDE提醒我,getMonth()和getYear()方法已过时.我想知道如何在较新的Java 7或Java 8中做同样的事情.
private boolean inCurrentMonth(Date givenDate) {
Date today = new Date();
return givenDate.getMonth() == today.getMonth() && givenDate.getYear() == today.getYear();
}
Run Code Online (Sandbox Code Playgroud)
小智 9
//Create 2 instances of Calendar
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
//set the given date in one of the instance and current date in the other
cal1.setTime(givenDate);
cal2.setTime(new Date());
//now compare the dates using methods on Calendar
if(cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
if(cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) {
// the date falls in current month
}
}
Run Code Online (Sandbox Code Playgroud)
使用新的java.time API(教程)有几种方法可以实现.你可以使用它.get(ChronoField.XY),但我认为这更漂亮:
Instant given = givenDate.toInstant();
Instant ref = Instant.now();
return Month.from(given) == Month.from(ref) && Year.from(given).equals(Year.from(ref));
Run Code Online (Sandbox Code Playgroud)
为了更好的可重用性,您还可以将此代码重构为"时间查询":
public class TemporalQueries {
//TemporalQuery<R> { R queryFrom(TemporalAccessor temporal) }
public static Boolean isCurrentMonth(TemporalAccessor temporal) {
Instant ref = Instant.now();
return Month.from(temporal) == Month.from(ref) && Year.from(temporal).equals(Year.from(ref));
}
}
Boolean result = givenDate.toInstant().query(TemporalQueries::isCurrentMonth); //Lambda using method reference
Run Code Online (Sandbox Code Playgroud)
其他答案忽略了时区的关键问题.巴黎的新日早些时候比蒙特利尔更新.所以在同一时刻,日期是不同的,巴黎的"明天"和蒙特利尔的"昨天".
与Java捆绑在一起的java.util.Date和.Calendar类是众所周知的麻烦,令人困惑和有缺陷的.避免他们.
而是使用Joda-Time库或Java 8中的java.time包(受Joda-Time启发).
这是Joda-Time 2.5中的示例代码.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( yourJUDate, zone ); // Convert java.util.Date to Joda-Time, and assign time zone to adjust.
DateTime now = DateTime.now( zone );
// Now see if the month and year match.
if ( ( dateTime.getMonthOfYear() == now.getMonthOfYear() ) && ( dateTime.getYear() == now.getYear() ) ) {
// You have a hit.
}
Run Code Online (Sandbox Code Playgroud)
有关更加通用的解决方案,看看片刻是否在任何时间范围内(不仅仅是一个月),请搜索StackOverflow中的"joda","interval"和"contains".
Java 8 提供了YearMonth表示给定年份(例如 2018 年 1 月)中给定月份的类。这可用于YearMonth与给定日期的进行比较。
private boolean inCurrentMonth(Date givenDate) {
ZoneId timeZone = ZoneOffset.UTC; // Use whichever time zone makes sense for your use case
LocalDateTime givenLocalDateTime = LocalDateTime.ofInstant(givenDate.toInstant(), timeZone);
YearMonth currentMonth = YearMonth.now(timeZone);
return currentMonth.equals(YearMonth.from(givenLocalDateTime));
}
Run Code Online (Sandbox Code Playgroud)
注意,这种方法适用于任何具有两个月份和日期部分(在Java 8次类的工作LocalDate,ZonedDateTime等等),而不是只LocalDateTime。
| 归档时间: |
|
| 查看次数: |
18091 次 |
| 最近记录: |