簡體   English   中英

如何在Java中用月份和年份顯示當前月份的日期?

[英]How to display date of a current month with the month and year in Java?

如何在Java中動態顯示for循環中特定月份的日期,月份和年份?

使用java.time

另一個答案使用麻煩的舊日期時間類(現已遺留),由java.time類取代。

LocalDate

LocalDate類表示沒有日期和時區的僅日期值。

時區

時區對於確定日期至關重要。 在任何給定時刻,日期都會在全球范圍內變化。 例如, 法國巴黎午夜過后幾分鍾是新的一天,而在魁北克蒙特利爾仍然是“昨天”。

continent/region的格式指定正確的時區名稱 ,例如America/MontrealAfrica/CasablancaPacific/Auckland 切勿使用ESTIST等3-4個字母的縮寫,因為它們不是真實的時區,不是標准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

YearMonth

我們關心整個月。 因此,使用YearMonth對象來表示該對象。

YearMonth ym = YearMonth.from( today );

獲取本月的第一天。

LocalDate localDate = ym.atDay( 1 );

循環播放,一次將日期增加一天,直到月末。 我們可以通過查看每個遞增的日期是否具有與今天相同的YearMonth來測試該事實。 將每個日期收集在一個List

List<LocalDate> dates = new ArrayList<>( 31 );  // Collect each date. We know 31 is maximum number of days in any month, so set initial capacity.
while( YearMonth.of( localDate).equals( ym ) ) {  // While in the same year-month.
    dates.add( localDate ); // Collect each incremented `LocalDate`.
    System.out.println( localDate );
    // Set up next loop.
    localDate = localDate.plusDays( 1 );
}

關於java.time

java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.DateCalendarSimpleDateFormat

現在處於維護模式Joda-Time項目建議遷移到java.time類。

要了解更多信息,請參見Oracle教程 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310

在哪里獲取java.time類?

ThreeTen-Extra項目使用其他類擴展了java.time。 該項目為將來可能在java.time中添加內容提供了一個試驗場。 您可以在這里找到一些有用的類,比如IntervalYearWeekYearQuarter ,和更多

這簡要演示了Java中SimpleDateFormatGregorianCalendar類的一些基礎知識。 根據您的問題,這是我能做的最好的事情。

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

public class Main {
    public static void main(String[] args) {
        int year = 2012;
        int month = 4;

        /* The format string for how the dates will be printed. */
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

        /* Create a calendar for the first of the month. */
        GregorianCalendar calendar = new GregorianCalendar(year, month, 1);

        /* Loop through the entire month, day by day. */
        while (calendar.get(GregorianCalendar.MONTH) == month) {
            String dateString = format.format(calendar.getTime());
            System.out.println(dateString);

            calendar.add(GregorianCalendar.DATE, 1);
        }
    }
}

暫無
暫無

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

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