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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28666335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:58:12  来源:igfitidea点击:

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

javaandroiddategetdate

提问by Robby

I'm using an int variable:

我正在使用一个 int 变量:

month = dp.getMonth() + 1;

currently getting an output of "2" and when I do the following:

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

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

I get: 50.

我得到:50。

回答by Simon M?Kenzie

Your problem is that your '0'charis being coerced to an integer. Since '0'has an ASCII value of 48, you're getting 48 + 2 = 50.

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

Note that what you're trying to do won't work - you can't add a leading 0to month, as monthis a number. A leading zero only makes sense in a string representationof a number.

请注意,您尝试执行的操作是行不通的 - 您不能像数字一样将前导添加0到。前导零仅在数字的字符串表示中有意义。monthmonth

As explained in this answer, here's how to produce a zero-padded number:

本答案所述,以下是生成零填充数字的方法:

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