Joda 时间 - 月中的某一天和一年中的某月 不返回 2 位数字输出

2022-09-03 16:25:17

我有以下代码:

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位数字检索月份和年份的值。


答案 1

你可以简单地使用 AbstractDateTime#toString(String)

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

答案 2

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

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

}

推荐