Java 无法使用withDayOfMonth获取月份的初始日期
我想获得给定日期时间的当月第一个日期时间,如下所示:对于日期Java 无法使用withDayOfMonth获取月份的初始日期,java,arraylist,java-stream,java-time,Java,Arraylist,Java Stream,Java Time,我想获得给定日期时间的当月第一个日期时间,如下所示:对于日期19-04-2018 19:00:00(dd-MM-yyy HH:MM:ss),它应该是01-04-2018 00:00:00 List<scPosR> scPosRListPerStoreAndTimeStamp = spst.stream().filter( scPosR -> Timestamp.valueOf(scPosR.getTransactionDate()
19-04-2018 19:00:00
(dd-MM-yyy HH:MM:ss),它应该是01-04-2018 00:00:00
List<scPosR> scPosRListPerStoreAndTimeStamp = spst.stream().filter(
scPosR -> Timestamp.valueOf(scPosR.getTransactionDate()
.toLocalDateTime()
.toLocalDate()
.withDayOfMonth(1)
.atStartOfDay())
.equals(startDate))
.collect(Collectors.toList());
我尝试了下面的代码,但它给出了一个空列表
startDate
可能包含类似01-04-2018 00:00:00
的值
List<scPosR> scPosRListPerStoreAndTimeStamp = spst.stream().filter(
scPosR -> Timestamp.valueOf(scPosR.getTransactionDate()
.toLocalDateTime()
.toLocalDate()
.withDayOfMonth(1)
.atStartOfDay())
.equals(startDate))
.collect(Collectors.toList());
List scPosRListPerStoreAndTimeStamp=spst.stream().filter(
scPosR->Timestamp.valueOf(scPosR.getTransactionDate())
.toLocalDateTime()
.toLocalDate()
.月日内(1)
.atStartOfDay())
.等于(起始日期))
.collect(Collectors.toList());
有谁能建议我做这件事吗?我说不出哪里出了问题。正如Pavan所观察到的,您的代码在我的计算机上也按预期工作,并返回一个列表,其中包含事务日期为4月份的对象。一种可能的解释是,如果您的
startDate
变量不包含Timestamp
,而是其他(运行时)类型。另一种可能的解释是时区问题:如果您的startDate
时间戳是在不同的时区创建的,那么它将不等于在流过滤器中创建的时间戳
无论如何,这里有一个更简单的代码版本,希望它也能更容易调试
YearMonth month = YearMonth.of(2018, Month.APRIL);
List<ScPosR> scPosRListPerStoreAndTimeStamp = spst.stream()
.filter(scPosR -> YearMonth.from(scPosR.getTransactionDate().toLocalDateTime())
.equals(month))
.collect(Collectors.toList());
YearMonth-month=YearMonth.of(2018年4月);
列表scPosRListPerStoreAndTimeStamp=spst.stream()
.filter(scPosR->YearMonth.from(scPosR.getTransactionDate().toLocalDateTime())
.等于(月))
.collect(Collectors.toList());
当然,如果您可以完全摆脱过时的
时间戳
类,那就更好了。您确定列表中至少包含一个具有匹配起始日期
值的对象吗?对于我来说,localDate.withDayOfMonth(1)。atStartDay()
返回期望值startDate的类型是什么?如果它不是时间戳
,等于
将返回false。