Java 确定该月的第一天是星期几,并存储从该位置开始的日数

Java 确定该月的第一天是星期几,并存储从该位置开始的日数,java,localdate,Java,Localdate,我试图用其中的日期填充数组 例如,本月8月,它应该显示 Sunday Monday Tuesday Wednesday ... Saturday null 1 2 3 ... 6 ... ... ... ... ... ... 它正在处理以下问题: import java.time.LocalDate; import java.util.Scanner; public class buildCa

我试图用其中的日期填充数组

例如,本月8月,它应该显示

Sunday Monday Tuesday Wednesday  ...  Saturday
null    1        2        3      ...     6
...     ...      ...     ...     ...     ...
它正在处理以下问题:

import java.time.LocalDate;
import java.util.Scanner;

public class buildCalendar {
    String[] calendar = new String[48];
    private final int firstDayOfMonth = 1;
    Scanner sc = new Scanner(System.in);
    int month, year;

    public buildCalendar() {
        System.out.println("Month: ");
        month = sc.nextInt();
        sc.nextLine();
        System.out.println("Year: ");
        year = sc.nextInt();

        newCalendar(month, year);
    }

    public void newCalendar(int month, int year) {
        LocalDate inputDate = LocalDate.of(year, month, firstDayOfMonth);
        int dayOfWeek = inputDate.withDayOfMonth(firstDayOfMonth).getDayOfWeek().getValue();


        // populate String array
        int i = 0;

        while (i <= calendar.length) {      
            if (i == dayOfWeek) {       
                for (int j = 0; j < inputDate.lengthOfMonth(); j++) {
                    calendar[i] = Integer.toString(i);
                    i++;                                    
                }
            }
            i++;
        }

        for (String string : calendar) {
            System.out.println(string);
        }
    }

}
假设5等于1。
你们将如何改变这一点?

因为我很无聊,我决定为此编写一个完整的类,但略有不同

我不是为天数创建一个
String[48]
数组,而是为月份的几周创建一个
int[weeks][7]
2D数组,其中
weeks
介于
4
6
之间,具体取决于月份的天数和月份第一天的工作日。值
0
为“空白”日

代码已增强为
Locale
aware,即确定一周是从周日开始(如美国)还是从周一开始(如欧洲大部分地区)

我还添加了一个漂亮的
print()
方法,它将在给定的
区域设置中打印月份,并自动调整输出大小

核心输入是识别月份的
YearMonth
Locale
。与代码类似的基本逻辑是以下7行:

this.firstWeekdayOfWeek = WeekFields.of(this.locale).getFirstDayOfWeek();
DayOfWeek firstWeekdayOfMonth = this.yearMonth.atDay(1).getDayOfWeek();
int startWeekDay = (firstWeekdayOfMonth.getValue() - this.firstWeekdayOfWeek.getValue() + 7) % 7;
int endWeekDay = startWeekDay + this.yearMonth.lengthOfMonth();
this.weekdays = new int[(endWeekDay + 6) / 7][7];
for (int weekDay = startWeekDay, dayOfMonth = 1; weekDay < endWeekDay; weekDay++, dayOfMonth++)
    this.weekdays[weekDay / 7][weekDay % 7] = dayOfMonth;
试验

输出

2016年8月
星期日星期一星期二星期三星期五星期六
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        31
2016年1月
星期日星期一星期二星期三星期五星期六
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
31
janvier 2016
我是杰迪·文德雷迪·萨梅迪·迪曼奇
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       31

如您所见,它调整为从周一开始的一周,这恰好将周数从6周减少到5周。

Wow非常感谢。明天早上我会看你的笔记。嘿,谢谢你的意见。你的团队运作得很好,我也发现了我明显的错误<代码>整数计数器=0;while(柜台)
this.firstWeekdayOfWeek = WeekFields.of(this.locale).getFirstDayOfWeek();
DayOfWeek firstWeekdayOfMonth = this.yearMonth.atDay(1).getDayOfWeek();
int startWeekDay = (firstWeekdayOfMonth.getValue() - this.firstWeekdayOfWeek.getValue() + 7) % 7;
int endWeekDay = startWeekDay + this.yearMonth.lengthOfMonth();
this.weekdays = new int[(endWeekDay + 6) / 7][7];
for (int weekDay = startWeekDay, dayOfMonth = 1; weekDay < endWeekDay; weekDay++, dayOfMonth++)
    this.weekdays[weekDay / 7][weekDay % 7] = dayOfMonth;
public final class CalendarMonth implements Comparable<CalendarMonth> {
    private final YearMonth yearMonth;
    private final Locale    locale;
    private final DayOfWeek firstWeekdayOfWeek;
    private final int[][]   weekdays;

    public static CalendarMonth of(int year, int month) {
        return new CalendarMonth(YearMonth.of(year, month), Locale.getDefault());
    }
    public static CalendarMonth of(int year, int month, Locale locale) {
        Objects.requireNonNull(locale, "locale");
        return new CalendarMonth(YearMonth.of(year, month), locale);
    }
    public static CalendarMonth of(int year, Month month) {
        return new CalendarMonth(YearMonth.of(year, month), Locale.getDefault());
    }
    public static CalendarMonth of(int year, Month month, Locale locale) {
        Objects.requireNonNull(locale, "locale");
        return new CalendarMonth(YearMonth.of(year, month), locale);
    }
    public static CalendarMonth of(YearMonth yearMonth) {
        Objects.requireNonNull(yearMonth, "yearMonth");
        return new CalendarMonth(yearMonth, Locale.getDefault());
    }
    public static CalendarMonth of(YearMonth yearMonth, Locale locale) {
        Objects.requireNonNull(yearMonth, "yearMonth");
        Objects.requireNonNull(locale, "locale");
        return new CalendarMonth(yearMonth, locale);
    }

    private CalendarMonth(YearMonth yearMonth, Locale locale) {
        this.yearMonth = yearMonth;
        this.locale = locale;

        // Build weekdays array
        this.firstWeekdayOfWeek = WeekFields.of(this.locale).getFirstDayOfWeek();
        DayOfWeek firstWeekdayOfMonth = this.yearMonth.atDay(1).getDayOfWeek();
        int startWeekDay = (firstWeekdayOfMonth.getValue() - this.firstWeekdayOfWeek.getValue() + 7) % 7;
        int endWeekDay = startWeekDay + this.yearMonth.lengthOfMonth();
        this.weekdays = new int[(endWeekDay + 6) / 7][7];
        for (int weekDay = startWeekDay, dayOfMonth = 1; weekDay < endWeekDay; weekDay++, dayOfMonth++)
            this.weekdays[weekDay / 7][weekDay % 7] = dayOfMonth;
    }

    public void print() {
        // Get day names and determine width of longest name
        String[] dayName = new String[7];
        for (int i = 0; i < 7; i++)
            dayName[i] = this.firstWeekdayOfWeek.plus(i).getDisplayName(TextStyle.FULL, this.locale);
        int width = Arrays.stream(dayName).mapToInt(String::length).max().getAsInt();

        // Print month name
        String title = this.yearMonth.format(DateTimeFormatter.ofPattern("MMMM uuuu", this.locale));
        System.out.println(rightTrim(center(title, width * 7 + 6)));

        // Print day names
        StringBuilder line = new StringBuilder();
        for (int i = 0; i < 7; i++)
            line.append(center(dayName[i], width)).append(' ');
        System.out.println(rightTrim(line.toString()));

        // Print day numbers
        for (int[] week : this.weekdays) {
            line.setLength(0);
            for (int i = 0; i < 7; i++)
                line.append(center((week[i] == 0 ? "" : String.format("%2d", week[i])), width)).append(' ');
            System.out.println(rightTrim(line.toString()));
        }
    }
    private static String center(String text, int width) {
        if (text.length() >= width)
            return text;
        char[] buf = new char[width];
        Arrays.fill(buf, ' ');
        System.arraycopy(text.toCharArray(), 0, buf, (width - text.length() + 1) / 2, text.length());
        return new String(buf);
    }
    private static String rightTrim(String text) {
        return text.replaceFirst("\\s+$", "");
    }

    @Override
    public String toString() {
        return this.yearMonth.toString();
    }
    @Override
    public int compareTo(CalendarMonth that) {
        int cmp = this.yearMonth.compareTo(that.yearMonth);
        if (cmp == 0)
            cmp = this.locale.toLanguageTag().compareTo(that.locale.toLanguageTag());
        return cmp;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj instanceof CalendarMonth) {
            CalendarMonth other = (CalendarMonth) obj;
            return (this.yearMonth.equals(other.yearMonth) &&
                    this.locale.equals(other.locale));
        }
        return false;
    }
    @Override
    public int hashCode() {
        return Objects.hash(this.yearMonth, this.locale);
    }
}
CalendarMonth.of(2016, Month.AUGUST).print();
CalendarMonth.of(2016, Month.JANUARY).print();
CalendarMonth.of(2016, Month.JANUARY, Locale.FRANCE).print();