[英]Joda Time - Day of month and Month of Year Not returning 2 digit output
我有以下代碼:
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位數的月份和年份的值。
你可以簡單地使用AbstractDateTime#toString(String)
System.out.println(" Month : "+ dateTime.toString("MM"));
System.out.println(" Day : "+ dateTime.toString("dd"));
另一種方法是使用十進制格式化程序
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());
}
}
你正在調用getMonthOfYear()
- getMonthOfYear()
返回一個int
。 它可能會比October
月提前一個月回報,這會讓您滿意嗎? 換句話說,讓我們把Joda Time從等式中解脫出來......你期望它的輸出是什么?
int month = 9;
System.out.println(" Month : " + month);
?
您需要了解數據 (本例中為整數)與所需的文本表示之間的差異。 如果你想要一個特定的格式,我建議你使用DateTimeFormatter
。 (無論如何,一次打印一個單獨的字段幾乎不是一個好主意......我原本希望你想要像“2013-09-08”這樣的單字符串。)
您還可以使用String.format
來控制輸出格式,或者使用DecimalFormat
或PrintStream.printf
- 有許多格式化整數的方法。 您需要了解數字9 只是數字9 - 它沒有與之關聯的格式。
例:
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.