Java – returns 1 to 7 days of the week from any given date interval
•
Java
I want to return a date map from the date interval:
>1 to 7 days:
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)
>The sorted map (week starts on Monday), the returned date is the key string (string), and the value is always = true (Boolean), which will be reused for other purposes
I want to use joda time 2.8 1, but I don't know how to deal with date interval? I managed to get what I wanted, but only for one day:
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
Solution
Joda time does not support (close) calendar date intervals, but only instantaneous intervals So here's a special solution:
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;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码