简体   繁体   中英

Calendar.MONTH return 2. How to return 02

String.valueOf(Calendar.getInstance().get(Calendar.MONTH) + 1) return 1 instead of 01. How can I use this that result will be 02, 03, 04 and not 2, 3, 4

I know that Calendar.MONTH return numbers from 0 to 11

http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#MONTH

This is a formatting issue. Why not investigate SimpleDateFormat ? Or String.format() ?

(note that SimpleDateFormat has thread-safety issues and Joda-Time is a recommended alternative)

您可以改用

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

Use SimpleDateFormat:

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
    System.out.println(dateFormat.format(date));

And I'd also recommend to use Joda Time instead of the Java Calendar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM