fork download
  1. import java.time.DayOfWeek;
  2. import java.time.LocalDate;
  3. import java.time.YearMonth;
  4. import java.time.format.DateTimeFormatter;
  5. import java.time.temporal.TemporalAdjusters;
  6. import java.time.temporal.WeekFields;
  7. import java.util.Locale;
  8. import java.util.stream.Collectors;
  9. import java.util.stream.IntStream;
  10.  
  11. public class Main {
  12. public static void main(String[] args) {
  13. // Let's test
  14. System.out.println(getMonthCalendar(Locale.UK));
  15. System.out.println("-+-+-+-+-+-+-+-+-+-+-+-+-+-");
  16. System.out.println(getMonthCalendar(Locale.US));
  17. }
  18.  
  19. static String getMonthCalendar(Locale locale) {
  20. LocalDate localDate = LocalDate.now();
  21. YearMonth ym = YearMonth.of(localDate.getYear(), localDate.getMonthValue());
  22. StringBuilder sb = new StringBuilder();
  23.  
  24. // First day of week
  25. DayOfWeek firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
  26.  
  27. LocalDate date = localDate.with(TemporalAdjusters.dayOfWeekInMonth(0, firstDayOfWeek));
  28. DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE", locale);
  29. sb.append(
  30. IntStream.rangeClosed(0, 6)
  31. .mapToObj(i -> dtf.format(date.plusDays(i)))
  32. .collect(Collectors.joining(" "))
  33. )
  34. .append(System.lineSeparator());
  35.  
  36. int counter = 1;
  37.  
  38. // Print as many space as the difference between the day of week of 1st date of
  39. // the month and the first day of the week in that Locale
  40. int dayValue = localDate.withDayOfMonth(1).getDayOfWeek().getValue() - firstDayOfWeek.getValue();
  41. dayValue = dayValue < 0 ? 7 + dayValue : dayValue;
  42. for (int i = 0; i < dayValue; i++, counter++) {
  43. sb.append(String.format("%-4s", ""));
  44. }
  45.  
  46. for (int i = 1; i <= ym.getMonth().length(ym.isLeapYear()); i++, counter++) {
  47. sb.append(String.format("%-4d", i));
  48.  
  49. // Break the line if the value of the counter is multiple of 7
  50. if (counter % 7 == 0) {
  51. sb.append(System.lineSeparator());
  52. }
  53. }
  54.  
  55. return sb.toString();
  56. }
  57. }
Success #stdin #stdout 0.26s 55400KB
stdin
Standard input is empty
stdout
Mon Tue Wed Thu Fri Sat Sun
        1   2   3   4   5   
6   7   8   9   10  11  12  
13  14  15  16  17  18  19  
20  21  22  23  24  25  26  
27  28  29  30  
-+-+-+-+-+-+-+-+-+-+-+-+-+-
Sun Mon Tue Wed Thu Fri Sat
            1   2   3   4   
5   6   7   8   9   10  11  
12  13  14  15  16  17  18  
19  20  21  22  23  24  25  
26  27  28  29  30