我正在尝试检查某个特定日期是否比今天日期早一周。我将我的日期格式化为这种格式:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
然后,我通过这些代码从 for 循环中获取日期列表:
Date formattedToday = formatter.parse(todayStr);
Date formattedExpired = formatter.parse(expiredDate);
列表中日期的例子是:
09/12/2017 08:09 PM
10/24/2015 02:09 AM
07/18/2018 03:10 AM
我试着关注 this thread但我不允许添加任何外部库。
需要 Java 8
的其他解决方案也不适用于我,因为我当前的最小 API 是 25 但 ChronoUnit
需要 API 26
。
有什么想法吗?谢谢!
最佳答案
tl;dr
ZonedDateTime
.now() // Captures current moment as seen by the wall-clock time of the JVM’s current default time zone. Better to pass the optional `ZoneId` argument to specify explicitly the desired/expected time zone.
.minusWeeks( 1 )
.isAfter(
LocalDateTime
.parse(
"09/12/2017 08:09 PM" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm a" , Locale.US )
)
.atZone(
ZoneId.systemDefault() // Better to pass explicitly the time zone known to have been intended for this input. See discussion below.
)
)
使用java.time
现代解决方案使用 java.time 类。使用可怕的旧遗留 Date
、Calendar
等要容易得多。
Check if date is one week before from today Java
您是否打算只处理日期,而忽略一天中的时间?我假设不会,因为您的输入有时间。
以 UTC 格式获取当前时刻。
Instant instant = Instant.now() ; // Current moment in UTC.
调整为隐含的时区作为日期时间输入字符串的上下文。应用 ZoneId
以获取 ZonedDateTime
对象。
指定 proper time zone name格式为continent/region
,如America/Montreal
, Africa/Casablanca
,或 太平洋/奥克兰
。切勿使用 3-4 个字母的缩写,例如 EST
或 IST
,因为它们不是真正的时区,不是标准化的,甚至不是唯一的( !)。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ; // Replace with the zone you know to have been intended for the input strings.
ZonedDateTime zdtNow = instant.atZone( z ) ; // Adjust from UTC to a time zone.
减去一周,即您在问题中陈述的要求。
ZonedDateTime zdtWeekAgo = zdtNow.minusWeeks( 1 ) ; // Accounts for anomalies such as Daylight Saving Time (DST).
将您的输入字符串解析为 LocalDateTime
对象,因为它们缺少任何时区指示符或与 UTC 的偏移量。
提示:如果可能的话,更改这些输入以包括它们的时区。并更改其格式以使用标准 ISO 8601 格式而不是自定义格式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm a" , Locale.US ) ;
LocalDateTime ldt = LocalDateTime.parse( "09/12/2017 08:09 PM" , f ) ;
为这些输入字符串指定您知道的时区。
ZonedDateTime zdt = ldt.atZone( z ) ;
比较。
boolean moreThanWeekOld = zdt.isBefore( zdtWeekAgo ) ;
关于java.time
java.time框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧类 legacy日期时间类,例如 java.util.Date
, Calendar
, & SimpleDateFormat
.
Joda-Time项目,现在在maintenance mode , 建议迁移到 java.time类。
要了解更多信息,请参阅 Oracle Tutorial .并在 Stack Overflow 中搜索许多示例和解释。规范为 JSR 310 .
您可以直接与您的数据库交换java.time 对象。使用 JDBC driver符合 JDBC 4.2或以后。不需要字符串,不需要 java.sql.*
类。
从哪里获得 java.time 类?
- > Java SE 8 , Java SE 9 , Java SE 10 , 然后
- 内置。
- 带有 bundle 实现的标准 Java API 的一部分。
- Java 9 添加了一些次要功能和修复。
- > Java SE 6和 Java SE 7
- 许多 java.time 功能在 ThreeTen-Backport 中被反向移植到 Java 6 和 7 .
- > Android
- 更高版本的 Android bundle 实现 java.time 类。
- 对于早期的 Android (<26),ThreeTenABP项目改编ThreeTen-Backport (上文提到的)。参见 How to use ThreeTenABP… .
关于java - 检查日期是否是从今天开始的一周前 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51470345/