return : Tue From: "201-6ren">
gpt4 book ai didi

java - 从任何给定的日期间隔返回一周的 1 到 7 天

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:23:21 24 4
gpt4 key购买 nike

我想从日期间隔返回天数图:

  1. 从 1 到 7 天:

         From: "2016-02-09" to To: "2016-02-09" -> return : Tue
    From: "2016-02-09" to To: "2016-02-12" -> return : Tue, Wed, Thu, Fri
    From: "2016-02-02" to To: "2016-04-12" -> return : Tue, Wed, Thu, Fri, Sat, Sun, Mon (this should be sorted from Monday for the map)
  2. 返回的日期作为键(字符串)和value always = true( boolean 值)的排序映射(周从星期一开始),将重复用于另一个目的。

我想使用 joda-time 2.8.1,但我不确定如何处理日期间隔?我设法得到了我想要的一部分,但只用了一天:

String input = "2016-02-09";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd" );
LocalDate localDate = formatter.parseLocalDate( input );
Locale locale = Locale.US;
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); //Result = Tue

最佳答案

Joda-Time 不支持(封闭的)日历日期间隔,但仅支持瞬间间隔。所以这里有一个临时解决方法:

LocalDate start = LocalDate.parse("2016-02-09");
LocalDate end = LocalDate.parse("2016-02-12");
if (start.isAfter(end)) {
return Collections.emptyMap();
}

LocalDate current = start;
Map<Integer, Boolean> map = new TreeMap<>();

do {
map.put(current.getDayOfWeek(), Boolean.TRUE);
current = current.plusDays(1);
} while (!current.isAfter(end) && map.size() < 7);

LocalDate ref = new LocalDate(2016, 2, 7); // sunday
DateTimeFormatter f = DateTimeFormat.forPattern("E").withLocale(Locale.US);
StringBuilder sb = new StringBuilder();

for (int dayOfWeek : map.keySet()) {
String output = f.print(ref.plusDays(dayOfWeek));
sb.append(", ");
sb.append(output);
}
System.out.println(sb.delete(0, 2).insert(0, "[").append(']').toString());
// [Tue, Wed, Thu, Fri]
return map;

关于java - 从任何给定的日期间隔返回一周的 1 到 7 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35296006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com