为什么没有在今天日期设置 LocalDate 值

why LocalDate value did'nt set on today date

所以我有 7 个不同的按钮,我想 sethint 每个 button 与当前 date++ 有序。

DateTimeFormatter dateFormater = DateTimeFormatter.ofPattern("d");
        ZoneId zone = ZoneId.of("Asia/Jakarta");
        LocalDate date = LocalDate.now(zone);
        int amount = 1;
        int buttonCount = 7;
        for (int i = 0; i < buttonCount; i++){
            hari1.setHint(date.format(dateFormater));
            date = date.plusDays(amount);
            hari2.setHint(date.format(dateFormater));
            date = date.plusDays(amount);
            hari3.setHint(date.format(dateFormater));
            date = date.plusDays(amount);
            hari4.setHint(date.format(dateFormater));
            date = date.plusDays(amount);
            hari5.setHint(date.format(dateFormater));
            date = date.plusDays(amount);
            hari6.setHint(date.format(dateFormater));
            date = date.plusDays(amount);
            hari7.setHint(date.format(dateFormater));
        }

日期输出开始27-28-29等。这是错误的,因为今天的日期是 22。输出应该是 22-23-24 等等吧?所以我尝试在日期上使用日历并且输出是正确的 22。为什么 ?有没有解决方案,所以我可以获得正确的日期并得到它(日期++)?还有另一种方法吗?怎么样?

        Date today = Calendar.getInstance().getTime();
        final SimpleDateFormat fcDate = new SimpleDateFormat("dd");

您的代码的问题在于,在循环的 7 次迭代中,您都将提示分配给所有按钮,因此您对每个按钮进行了 7 次分配,总共 49 次分配,增加了每次之后的日期分配,所以你到达了这些不正确的日期。
所以结果是您看到上次迭代分配的值显然是错误的。
在每次迭代中对 1 个按钮进行 1 次赋值,如下所示:

DateTimeFormatter dateFormater = DateTimeFormatter.ofPattern("d");
ZoneId zone = ZoneId.of("Asia/Jakarta");
LocalDate date = LocalDate.now(zone);
int amount = 1;
int buttonCount = 7;
for (int i = 0; i < buttonCount; i++){
    int buttonId = getResources().getIdentifier("hari_" + (i + 1), "id", getPackageName()); 
    Button button = (Button) findViewById(buttonId);
    button.setHint(date.format(dateFormater));
    date = date.plusDays(amount);
}

这一行:

int buttonId = getResources().getIdentifier("hari_" + (i + 1), "id", getPackageName());

你得到每个按钮的整数 id 和这一行:

Button button = (Button) findViewById(buttonId);

你得到一个引用按钮的变量。

使用流

是正确的。为了这里的乐趣,让我们尝试使用流。我不是声称这比其他第一个解决方案更好,只是一个替代方案。

我们用 IntStream 数到七。我们使用生成的整数将天数添加到当前日期,并使用其他答案中显示的命名方法访问特定按钮。

而不是通过DateTimeFormatter to get a day-of-month, we call LocalDate::getDayOfMonth. Convert from int to string via String.valueOf

我没有尝试 运行 这段代码,因为我不做 Android 工作。但希望它接近工作。

ZoneId z = ZoneId.of( "Asia/Jakarta" ) ;
LocalDate today = LocalDate.now( z ) ;

IntStream
.range( 0 ,  7 )
.forEach( 
    i -> 
    ( 
        (Button) findViewById( 
            getResources().getIdentifier( "hari_" + (i + 1), "id" , getPackageName() )   // See:   
        ) 
    )                         // Returns a `Button`.
    .setHint ( 
        String.valueOf(       // Convert int (day-of-month) to text.
            today
            .plusDays( i )    // Produces a new `LocalDate` object rather than modifying the original (immutable objects). 
            .getDayOfMonth()  // Returns an `int`. 
        )
    )  
    ;
)
;