java – 从任何给定的日期间隔返回一周的1到7天
发布时间:2020-12-15 04:32:20 所属栏目:Java 来源:网络整理
导读:我想从日期间隔返回一张日期地图: 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,Fri,Sat,Sun,Mon (this s
我想从日期间隔返回一张日期地图:
> 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,Fri,Sat,Sun,Mon (this should be sorted from Monday for the map) >排序的地图(周从星期一开始),返回的日期为关键字符串(字符串),值为always = true(布尔值),将重新用于其他目的. 我想使用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,Fri] return map; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |