Joda Time - Day of month and Month of Year Not returning 2 digit output
You're calling getMonthOfYear()
- that just returns an int
. What value could it possibly return for a month earlier than October
which would satisfy you? To put it another way, let's take Joda Time out of the equation... what would you expect the output of this to be?
int month = 9;
System.out.println(" Month : " + month);
?
You need to understand the difference between data (an integer in this case) and the textual representation you want for that integer. If you want a specific format, I suggest you use DateTimeFormatter
. (It's very rarely a good idea to print out a single field at a time anyway... I would have expected you to want something like "2013-09-08" as a single string.)
You could also use String.format
to control the output format, or DecimalFormat
, or PrintStream.printf
- there are any number of ways of formatting integers. You need to understand that the number 9 is just the number 9 though - it doesn't have a format associated with it.
An alternative way would be using decimal formater
DecimalFormat df = new DecimalFormat("00");
==========================================================================================
import java.text.DecimalFormat;
import org.joda.time.DateTime;
public class Collectionss {
public static void main(String[] args){
DecimalFormat df = new DecimalFormat("00");
org.joda.time.DateTime dateTime = new DateTime();
System.out.println(" Year : "+dateTime.getYear());
System.out.println(" Month : "+ df.format(dateTime.getMonthOfYear()));
System.out.println(" Day : "+dateTime.getDayOfMonth());
}
}
You can simply use AbstractDateTime#toString(String)
System.out.println(" Month : "+ dateTime.toString("MM"));
System.out.println(" Day : "+ dateTime.toString("dd"));