Joda Time - Day of the month and month of the year 2-digit output is not returned

I have the following code:

String dateUTC = "2013-09-08T10:23:54.663-04:00"; org.joda.time.DateTime dateTime = new DateTime(dateUTC); System.out.println(" Year : " + dateTime.getYear()); System.out.println(" Month : " + dateTime.getMonthOfYear()); System.out.println(" Day : " + dateTime.getDayOfMonth()); The Output of this program is : Year : 2013 Month : 9 // I want this to be 2 digit if the month is between 1 to 9 Day : 8 // I want this to be 2 digit if the month is between 1 to 9 

Is there a way to get the month and year value in 2 digits using the Joda API.

+12
java jodatime
source share
4 answers

An alternative way would be to use decimal formatting

  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()); } } 
+19
source share

You can just use AbstractDateTime#toString(String)

 System.out.println(" Month : "+ dateTime.toString("MM")); System.out.println(" Day : "+ dateTime.toString("dd")); 
+36
source share

You call getMonthOfYear() - it just returns an int . What value could he return a month earlier than October , which will satisfy you? In other words, let me take the Joda Time out of the equation ... what do you expect from the conclusion of this?

 int month = 9; System.out.println(" Month : " + month); 

?

You need to understand the difference between the data (the whole in this case) and the textual representation you want for this whole. If you need a specific format, I suggest you use DateTimeFormatter . (It is very rare that you need to print one field at a time ... I would expect you to want something like "2013-09-08" as a single line.)

You can also use String.format to control the output format, or DecimalFormat or DecimalFormat — there are many ways to format integers. You need to understand that the number 9 is just the number 9, but it does not have a format associated with it.

+3
source share

Example:

 Calendar c = Calendar.getInstance(); System.out.format("%tB %te, %tY%n", c, c, c); // --> "September 10, 2013" System.out.format("%tl:%tM %tp%n", c, c, c); // --> "01:59 pm" System.out.format("%tD%n", c); // --> "09/10/13" 
-one
source share

All Articles