Java Joda Time-不返回2位数输出的月份和月份的日期

Java Joda Time-不返回2位数输出的月份和月份的日期,java,jodatime,Java,Jodatime,我有以下代码: 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("

我有以下代码:

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

是否有任何方法可以使用Joda API以2位数检索月份和年份的值。

您正在调用
getMonthOfYear()
-它只返回一个
int
。在10月之前的一个月内,它可能返回什么值,这会让您满意?换一种说法,让我们把乔达的时间从等式中去掉。。。你期望这个的输出是什么

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

您需要了解数据(在本例中为整数)与该整数所需的文本表示之间的差异。如果你想要一个特定的格式,我建议你使用。(无论如何,一次打印一个字段并不是一个好主意……我本以为您会想要像“2013-09-08”这样的字符串。)


您还可以使用来控制输出格式,或
DecimalFormat
,或-有多种格式化整数的方法。您需要了解数字9只是数字9,它没有与之关联的格式。

另一种方法是使用十进制格式化程序

 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()); 
    }

}
你可以简单地使用

例如:

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"

如果月份在1到9之间,我希望这个数字是2位数,这有什么意义?@SotiriosDelimanolis 01-09我希望月份为09,日期为08在这个具体的例子中,他甚至可以
month@Cruncher:是的,但我怀疑在实际需求中,使用
DateTimeFormatter
将是一种可行的方法。我听说,但是我可以使用DateTimeFormatter获取和示例,它将以2位数字返回月份和日期吗format@JavaCoderDateTimeFormatter在他们的API中。有太多不同的方式来格式化日期,如果对所有的日期都有一个重载是不切实际的。所以他们使用格式化程序类。@JavaCoder:不,不应该,依我看。单一责任原则适用。
DateTime
负责告诉你月份是什么,等等-格式化程序负责格式化。最简单、最直接的答案。但愿我能想到它+1.我会选择你的解决方案,看起来简单明了。虽然这个解决方案有效,但莱默斯下面的答案是正确的。你是一个救命恩人。非常感谢。
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"