如何使用 Java 以短格式显示月份名称
在本教程中,我们将使用 Java 中的 SimpleDateFormat 类,使用完整月份名称 (MMMM 格式) 格式化当前月份。通过指定模式"MMMM",您可以检索并显示完整的月份名称,如"January"、"February"等。以下是以短格式显示月份名称的不同方法 -
使用 DateFormatSymbols 显示短月份名称
在不同区域设置中格式化日期
使用 DateFormatSymbols 显示短月份名称
DateFormatSymbols 类提供有关日期和时间(包括月份名称)的格式和解析的语言敏感信息。
getShortMonths(): DateFormatSymbols 的 getShortMonths 方法 返回短月份名称的数组(例如, "Jan"、"Feb"等)。
示例
以下示例借助 DateFormatSymbols 类的 DateFormatSymbols().getShortMonths() 方法以简短形式显示月份名称 −
import java.text.SimpleDateFormat;
import java.text.DateFormatSymbols;
public class Main {
public static void main(String[] args) {
String[] shortMonths = new DateFormatSymbols().getShortMonths();
for (int i = 0; i < (shortMonths.length-1); i++) {
String shortMonth = shortMonths[i];
System.out.println("shortMonth = " + shortMonth);
}
}
}
输出
shortMonth = Jan shortMonth = Feb shortMonth = Mar shortMonth = Apr shortMonth = May shortMonth = Jun shortMonth = Jul shortMonth = Aug shortMonth = Sep shortMonth = Oct shortMonth = Nov shortMonth = Dec
在不同地区设置日期格式
地区:表示特定地理、政治或文化区域的类。它会影响某些信息(如月份名称或日期格式)的显示方式。 Locale.FRENCH 和 Locale.ENGLISH 分别代表法语和英语地区。
Calendar getInstance():Java Calendar getInstance() 方法 使用当前时区和语言环境获取日历。
语法
以下是 Calendar getInstance() 的语法
public static Calendar getInstance()
示例
以下是日期、时间和短月份的另一个示例 -
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;
public class Main {
public static void main(String[] argv) throws Exception {
String str1 = "dd-MMM-yy"; // Format pattern
Date d = Calendar.getInstance().getTime(); // Get the current date and time
// 法语区域格式
SimpleDateFormat sdf = new SimpleDateFormat(str1, Locale.FRENCH);
System.out.println("French Locale: " + sdf.format(d)); // Output in French Locale
// 格式化为英语区域设置
sdf = new SimpleDateFormat(str1, Locale.ENGLISH);
System.out.println("English Locale: " + sdf.format(d)); // Output in English Locale
}
}
输出
French Locale: 09-d?c.-24 English Locale: 09-Dec-24

