如何在 Java (Android) 中使用 getMonth 添加前导零

How to add Leading Zero with getMonth in Java (Android)

我正在使用一个 int 变量:

month = dp.getMonth() + 1;

当前得到“2”的输出,当我执行以下操作时:

if (month<10){
                month = '0'+month;
            };

我得到:50。

您的问题是您的 '0' char 被强制转换为整数。由于 '0' 的 ASCII 值为 48,您将得到 48 + 2 = 50.

请注意,您尝试执行的操作不会起作用 - 您不能将前导 0 添加到 month,因为 month 是一个数字。前导零仅在数字的 字符串表示形式 中有意义。

this answer 中所述,以下是生成零填充数字的方法:

String.format("%02d", month);