问题描述
我要转换以下字符串:
private String cw = "35/19"
分为2个日期。
开始日期可以使用以下格式设置:
private final DateTimeFormatter startOfWeekFormat = new DateTimeFormatterBuilder()
.appendPattern("ww/YY")
.parseDefaulting(WeekFields.ISO.dayOfWeek(),1)
.toFormatter();
在调用时返回:26.08.2019
LocalDate.parse(cw,startOfWeekFormat).atStartOfDay();
但是我很难忍受这周的结束,这基本上是下周“ 36/19”的开始。
我尝试添加8天以上,但这引发了异常:
private final DateTimeFormatter endOfWeekFormat = new DateTimeFormatterBuilder()
.appendPattern("ww/YY")
.parseDefaulting(WeekFields.ISO.dayOfWeek(),8)
.toFormatter();
解决方法
LocalDateTime ldt=LocalDate.parse(cw,startOfWeekFormat)
.atStartOfDay()
.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
演示:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
public class Main {
public static void main(String[] args) {
String cw = "35/19";
final DateTimeFormatter startOfWeekFormat = new DateTimeFormatterBuilder()
.appendPattern("ww/YY")
.parseDefaulting(WeekFields.ISO.dayOfWeek(),1)
.toFormatter();
LocalDateTime ldt=LocalDate.parse(cw,startOfWeekFormat)
.atStartOfDay()
.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println(ldt);
}
}
输出:
2019-09-02T00:00
,
另一个答案增加了一个星期,但以不同的方式:
我假设您总是想要一个日历周的开始日期和结束日期。您可以编写一个返回$validParams = @('opt1','opt2')
的方法,其中键是开始日期,值是结束日期。
它可能看起来像这样:
{ $_ -in $validParams }
像这样用示例Map.Entry<LocalDate,LocalDate>
在public static Map.Entry<LocalDate,LocalDate> getStartAndEndOfCalendarWeek(String calendarWeek) {
DateTimeFormatter startOfWeekFormatter = new DateTimeFormatterBuilder()
.appendPattern("ww/YY")
.parseDefaulting(WeekFields.ISO.dayOfWeek(),1)
.toFormatter();
LocalDate weekStart = LocalDate.parse(calendarWeek,startOfWeekFormatter);
LocalDate weekEnd = weekStart.plusWeeks(1);
return new AbstractMap.SimpleEntry<LocalDate,LocalDate>(weekStart,weekEnd);
}
中打印结果
main
将输出
String
我知道这会使使用您的public static void main(String[] args) {
String cw = "35/19";
Map.Entry<LocalDate,LocalDate> calendarWeekStartAndEndDate
= getStartAndEndOfCalendarWeek(cw);
System.out.println(calendarWeekStartAndEndDate.getKey()
+ " - " + calendarWeekStartAndEndDate.getValue());
}
解析2019-08-26 - 2019-09-02
的结果增加一个星期,但是我不认为涉及两个不同的解析器或进行解析操作不会比增加一个星期带来任何好处
如果您希望连续两个日历周开始,那么添加操作会增加另一天,如下所示:
DateTimeFormatter
,如果您想使用String
(如果确实需要,对我来说还不太清楚),那么您当然可以调整返回类型,并在解析{{1}时使用LocalDate weekEnd = weekStart.plusWeeks(1).plusDays(1);
},添加项将保持不变。
我希望不需要额外的日子的解决方案 到解析的字符串的结果。就像解决方案 格式器中已经包含“ plus(8)”。
那是不可能的。您无法将2020-08-30
解析为2020-08-31或2020-09-30。同样,您无法将35/19
解析为2019年第36周的日期。
我都赞成半开时间间隔,因此我确实认为在您的情况下这是可行的。抱歉,这是不可能的。
链接:WolframMathWorld中的Half-Open Interval。