如何在Java中显示当月与日期和月份的日期?

时间:2012-03-30 11:47:25

标签: java date

如何在Java中动态循环显示特定月份的日期,月份和年份?

2 个答案:

答案 0 :(得分:0)

这简要说明了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);
        }
    }
}

答案 1 :(得分:0)

使用java.time

另一个答案使用麻烦的旧日期时间类,现在是旧的,由java.time类取代。

LocalDate

LocalDate类表示没有时间且没有时区的仅限日期的值。

时区

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

continent/region的格式指定proper time zone name,例如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及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和&amp; SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

相关问题