Java 程式列出短月份名稱
在本文中,我們將學習如何在 Java 中列出短月份名稱。為此,我們將使用來自 java.text 包的 DateFormatSymbols 類。
java.text:此包提供用於管理文字、日期、數字和訊息的類和介面,其方式不依賴於任何特定語言。
DateFormatSymbols 是一個類,可幫助您處理可適應不同語言和地區的日期和時間資訊。它包括月份名稱、星期幾名稱以及有關時區的資訊。
問題陳述
編寫一個 Java 程式,列出所有月份的簡稱。
輸出
Month [0] = Jan
Month [1] = Feb
Month [2] = Mar
Month [3] = Apr
Month [4] = May
Month [5] = Jun
Month [6] = Jul
Month [7] = Aug
Month [8] = Sep
Month [9] = Oct
Month [10] = Nov
Month [11] = Dec
列出短月份名稱的步驟
以下是列出短月份名稱的步驟:
- 首先,我們將從 java.text 包匯入 DateFormatSymbols 類。
- 初始化 Demo 類。
- 使用 getShortMonths() 方法檢索短月份名稱。
- 使用 for 迴圈 遍歷短月份名稱陣列。
- 列印每個月份及其對應的索引。
Java 程式列出短月份名稱
以下是一個示例:
import java.text.DateFormatSymbols;
public class Demo {
public static void main(String[] args) {
// short months
String[] months = new DateFormatSymbols().getShortMonths();
for (int i = 0; i < months.length - 1; i++) {
String month = months[i];
System.out.println("Month ["+i+"] = " + month);
}
}
}
輸出
Month [0] = Jan Month [1] = Feb Month [2] = Mar Month [3] = Apr Month [4] = May Month [5] = Jun Month [6] = Jul Month [7] = Aug Month [8] = Sep Month [9] = Oct Month [10] = Nov Month [11] = Dec
程式碼解釋
在此程式中,我們首先從 java.text 包匯入 DateFormatSymbols 類。DateFormatSymbols 類用於封裝可本地化的日期時間格式化資料,其中包括月份名稱。然後,我們使用 getShortMonths() 方法獲取一個短月份名稱陣列,例如“Jan”、“Feb”等。
獲取此陣列後,我們使用 for 迴圈遍歷它,迴圈從 0 到 months.length - 1,以避免陣列中最後一個空元素。在迴圈內部,每個月份的名稱與其索引一起使用 System.out.println() 列印。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP