簡體   English   中英

我怎樣才能得到現在的月份?

[英]How can I get present months?

我試過

Calendar calendar= Calendar.getInstance();
System.out.println("use with command get time \"calendar.getTime()\"           : "+calendar.getTime());
System.out.println("use with command get month \"calendar.get(Calendar.MONTH)\": "+calendar.get(Calendar.MONTH));

但我找不到正確的月份。

這是我的 output

我怎樣才能得到當前月份? 感謝閱讀,抱歉我的英語不好。

java.time.LocalDate

您可以在下面使用 int 或 string 獲取月份值

LocalDate.now().getMonthValue();
LocalDate.now().getMonth();

您還可以使用SimpleDateFormat方法獲取當前日期和時間。

在這里看到我的function我得到當前的日期和時間供你參考

private void getTime(TextView dateTime) {
    Date date = new Date();
    @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE, d MMM yyyy HH:mm:ss aaa");
    dateTime.setText(simpleDateFormat.format(date));
}

更多信息,您可以在這里參考android官方文檔

以下是官方文檔中的一些示例。 參考鏈接

SimpleDateFormat sdf = new SimpleDateFormat("MM");
Date date = new Date();
Log.d("MyTag", sdf.format(date));

這里MM以 integer 形式表示月份 (dec ~ 12) 這里MMM以字母表示月份 (Dec)

Sriram 的回答是正確的,並使用java.time.LocalDate class 提供了現代解決方案。這里有一些更多的細節。

時區

LocalDate#now方法隱式使用 JVM 當前的默認時區。 時區很重要,因為對於任何給定時刻,時間以及日期在全球范圍內都可能因時區而異。 在日本東京可能是“明天”,而在美國俄亥俄州托萊多可能是“昨天”。

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;

如果您忽略傳遞ZoneId object,則會自動應用 JVM 的當前默認時區。 這與顯式傳遞默認值具有相同的效果。

LocalDate today = LocalDate.now( ZoneId.systemDefault() ) ;

我建議使用明確的方法來使您的意圖一目了然。

Month枚舉

LocalDate#getMonth方法返回Month枚舉 object。

Month month = LocalDate.now().getMonth() ;

如果您想生成文本來表示該值,您可以自動本地化。

Locale locale = Locale.CANADA_FRENCH ;
String output = month.getDisplayName( TextStyle.FULL , locale ) ;

請參閱在 Ideone.com 運行的這段代碼

十二月

您可以通過調用Locale.getDefault()來訪問 JVM 的當前默認語言環境。

Android

Android 26+ 實現了java.time類。

對於早期的 Android,使用最新的工具通過“API 脫糖”訪問大部分java.time功能。

如果查看 class java.util.Calendar的源代碼,您會發現以下常量:

    /**
     * Value of the {@link #MONTH} field indicating the
     * twelfth month of the year in the Gregorian and Julian calendars.
     */
    public static final int DECEMBER = 11;

因此calendar.get(Calendar.MONTH))正確返回 11(十一)。

但是,Android 8(API 級別 26)添加了 class LocalDate ,應該使用它代替 class Calendar 請注意,class Calendar包含日期和時間,而 class LocalDate僅包含日期。 Class LocalDateTime包含日期和時間。 還有 class LocalTime

根據now [static] 方法的文檔,在 class LocalDate中:

從默認時區的系統時鍾獲取當前日期。

如果你想要當前月份,你可以調用方法getMonthValue哪個......

獲取從 1 到 12 的月份字段。

或者,您可以調用getMonth方法,它...

使用Month枚舉獲取年月字段。

所以你的代碼應該是:

java.time.LocalDate calendar = java.time.LocalDate.now();
System.out.println("calendar           : " + calendar);
System.out.println("calendar.getMonth(): " + calendar.getMonth());

產生以下 output:

calendar           : 2022-12-30
calendar.getMonth(): DECEMBER

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM