【问题标题】:How to get start and end date of a year?如何获得一年的开始和结束日期?
【发布时间】:2012-03-12 01:53:03
【问题描述】:

我必须使用 Java Date 类来解决这个问题(它与我无法控制的东西交互)。

如何获取一年的开始和结束日期,然后遍历每个日期?

【问题讨论】:

  • 日期已去除。请改用日历。
  • 那么,Calendar 不是一个选项吗? @Stas:这不是真的。一堆不推荐使用的方法不会使整个类被弃用。
  • @Stas:不推荐使用相应的方法,而不是类本身。
  • @stas:药物不好。不要这样做。
  • DateCalendar 都已过时且设计不佳。请改用java.time

标签: java date


【解决方案1】:

java.time.YearMonth

如何获取特定年份和月份的第一个日期和最后一个日期。

这是使用YearMonth 类的代码。

YearMonthjava.time 包中的最后一个类,在 Java 8 中引入。

public static void main(String[] args) {

    int year = 2021;  // you can pass any value of year Like 2020,2021...
    int month = 6;   // you can pass any value of month Like 1,2,3...
    YearMonth yearMonth = YearMonth.of( year, month );  
    LocalDate firstOfMonth = yearMonth.atDay( 1 );
    LocalDate lastOfMonth = yearMonth.atEndOfMonth();

    System.out.println(firstOfMonth);
    System.out.println(lastOfMonth);
}

看到这个code run live at IdeOne.com

2021-06-01

2021-06-30

【讨论】:

  • 这是一种很好的方式来做你正在做的事情。问题是关于的第一天和最后一天。
  • 您正朝着正确的方向前进,但问题是针对 的第一个和最后一个,而不是 。您可以修改此答案以通过Year#atMonthYear 类与YearMonth 结合使用:Year.of( 2021 ).atMonth( Month.JANUARY ).atDay( 1 )Year.of( 2021 ).atMonth( Month.JANUARY ).atEndOfMonth()。或使用Year#atMonthDay
【解决方案2】:
val instance = Calendar.getInstance()
                instance.add(Calendar.YEAR,-1)

 val prevYear = SimpleDateFormat("yyyy").format(DateTime(instance.timeInMillis).toDate())

val firstDayPreviousYear = DateTime(prevYear.toInt(), 1, 1, 0, 0, 0, 0)

val lastDayPreviousYear = DateTime(prevYear.toInt(), 12, 31, 0, 0, 0, 0)

【讨论】:

  • 这些可怕的日期时间类在几年前被 JSR 310 中定义的 java.time 类所取代。建议在 2019 年使用它们是糟糕的建议。在Answer by Przemek 中查看现代解决方案。
【解决方案3】:

一年中的第一天和最后一天

import java.util.Calendar
import java.text.SimpleDateFormat

val parsedDateInt = new SimpleDateFormat("yyyy-MM-dd")

val cal2 = Calendar.getInstance()
cal2.add(Calendar.MONTH, -(cal2.get(Calendar.MONTH)))
cal2.set(Calendar.DATE, 1)
val firstDayOfYear = parsedDateInt.format(cal2.getTime)


cal2.add(Calendar.MONTH, (11-(cal2.get(Calendar.MONTH))))
cal2.set(Calendar.DATE, cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
val lastDayOfYear = parsedDateInt.format(cal2.getTime)

【讨论】:

  • 这些可怕的旧遗留类在几年前被现代 java.time 类所取代。建议在 2018 年使用它们是糟糕的建议。
【解决方案4】:
Calendar cal = Calendar.getInstance();//getting the instance of the Calendar using the factory method
we have a get() method to get the specified field of the calendar i.e year

int year=cal.get(Calendar.YEAR);//for example we get 2013 here 

cal.set(year, 0, 1); setting the date using the set method that all parameters like year ,month and day
Here we have given the month as 0 i.e Jan as the month start 0 - 11 and day as 1 as the days starts from 1 to30.

Date firstdate=cal.getTime();//here we will get the first day of the year

cal.set(year,11,31);//same way as the above we set the end date of the year

Date lastdate=cal.getTime();//here we will get the last day of the year

System.out.print("the firstdate and lastdate here\n");

【讨论】:

  • 请您解释一下您的代码好吗?目前不是很有帮助。
【解决方案5】:

如果你正在寻找单行表达式,我通常使用这个:

new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(new java.util.Date().getYear())+"-01-01")

【讨论】:

    【解决方案6】:

    更新: Joda-Time 库现在处于维护模式,其团队建议迁移到 java.time 类。查看正确的java.time Answer by Przemek

    时区

    其他答案忽略了时区的关键问题。

    乔达时间

    避免使用臭名昭著的麻烦 java.util.Date 类进行日期时间工作。而是使用 Joda-Time 或 java.time。根据需要转换为 j.u.Date 对象以实现互操作性。

    DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
    int year = 2015 ;
    DateTime firstOfYear = new DateTime( year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone ) ;
    DateTime firstOfNextYear = firstOfYear.plusYears( 1 ) ;
    DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays( 1 ) ;
    

    转换为java.util.Date

    根据需要转换为 j.u.Date。

    java.util.Date d = firstOfYear.toDate() ;
    

    【讨论】:

      【解决方案7】:

      对斯里尼的回答有所改进。
      使用Calendar.getActualMaximum 确定一年中的最后一个日期。

      Calendar cal = Calendar.getInstance();
      
      calDate.set(Calendar.DAY_OF_YEAR, 1);
      Date yearStartDate = calDate.getTime();
      
      calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR));
      Date yearEndDate = calDate.getTime();
      

      【讨论】:

        【解决方案8】:

        java.time

        使用 Java 8 及更高版本中内置的 java.time 库。特别是 LocalDateTemporalAdjusters 类。

        import java.time.LocalDate
        import static java.time.temporal.TemporalAdjusters.firstDayOfYear
        import static java.time.temporal.TemporalAdjusters.lastDayOfYear
        
        LocalDate now = LocalDate.now(); // 2015-11-23
        LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01
        LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31
        

        如果您需要添加时间信息,您可以使用任何可用的LocalDateLocalDateTime 转换,如

        lastDay.atStartOfDay(); // 2015-12-31T00:00
        

        【讨论】:

        • 好答案。我建议始终将所需/预期的时区传递给 LocalDate.now( ZoneId ),而不是隐式依赖 JVM 当前的默认时区,该时区在运行时随时可能更改。 LocalDate.now( ZoneId.of( "America/Montreal" ) ) 同样,始终将ZoneId 传递给atStartOfDay 方法,而不是隐式依赖JVM 默认值。 lastDay.atStartOfDay( ZoneID.of( "America/Montreal" ) )
        【解决方案9】:
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2014);
        cal.set(Calendar.DAY_OF_YEAR, 1);    
        Date start = cal.getTime();
        
        //set date to last day of 2014
        cal.set(Calendar.YEAR, 2014);
        cal.set(Calendar.MONTH, 11); // 11 = december
        cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve
        
        Date end = cal.getTime();
        
        //Iterate through the two dates 
        GregorianCalendar gcal = new GregorianCalendar();
        gcal.setTime(start);
        while (gcal.getTime().before(end)) {
            gcal.add(Calendar.DAY_OF_YEAR, 1);
            //Do Something ...
        }
        

        【讨论】:

        • 啊,我没有意识到你可以在日历和日期之间转换!
        • 你不能在它们之间转换;日期代表时间的瞬间,而日历告诉您该瞬间在特定系统中的表示方式。
        • 这段代码可以用cal.set(Calendar.MONTH, Calendar.DECEMBER);等常量改进
        【解决方案10】:
        GregorianCalendar gcal = new GregorianCalendar();
        gcal.setTime(start);
        while (gcal.getTime().before(end)) {
            gcal.add(Calendar.DAY_OF_YEAR, 1);
            //Do Something ...
        }
        

        这里的 GregorianCalendar 创作毫无意义。事实上,通过 Calendar.java 源代码可以发现 Calendar.getInstance() 已经给出了一个 GregorianCalendar 实例。

        问候, 尼古拉斯

        【讨论】:

          【解决方案11】:

          您可以使用具有 DateUtils 类的 apache commons-lang 项目。

          它们提供了一个迭代器,您可以将它提供给 Date 对象。

          但我强烈建议按照其他答案的建议使用 Calendar 类。

          【讨论】:

            【解决方案12】:
             Calendar cal = new GregorianCalendar();
                 cal.set(Calendar.DAY_OF_YEAR, 1);
                 System.out.println(cal.getTime().toString());
                 cal.set(Calendar.DAY_OF_YEAR, 366); // for leap years
                 System.out.println(cal.getTime().toString());
            

            【讨论】:

            • 这是否适用于非闰年?还是应该手动更正?
            • 请记住,有些年份有 365 天,有些年份有 366 天。我不应该使用这种方法。
            【解决方案13】:

            我假设您有 Date 类实例,并且您需要根据 Date 类实例查找当年的第一个日期和最后一个日期。您可以为此使用 Calendar 类。使用提供的日期类实例构造日历实例。将 MONTH 和 DAY_OF_MONTH 字段分别设置为 0 和 1,然后使用 getTime() 方法返回代表一年中第一天的 Date 类实例。您可以使用相同的技术来查找年终。

                Date date = new Date();
                System.out.println("date: "+date);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
            
                System.out.println("cal:"+cal.getTime());
            
                cal.set(Calendar.MONTH, 0);
                cal.set(Calendar.DAY_OF_MONTH, 1);
            
                System.out.println("cal new: "+cal.getTime());
            

            【讨论】:

              【解决方案14】:
                  // suppose that I have the following variable as input
                  int year=2011;
                  Calendar calendarStart=Calendar.getInstance();
                  calendarStart.set(Calendar.YEAR,year);
                  calendarStart.set(Calendar.MONTH,0);
                  calendarStart.set(Calendar.DAY_OF_MONTH,1);
                  // returning the first date
                  Date startDate=calendarStart.getTime();
              
                  Calendar calendarEnd=Calendar.getInstance();
                  calendarEnd.set(Calendar.YEAR,year);
                  calendarEnd.set(Calendar.MONTH,11);
                  calendarEnd.set(Calendar.DAY_OF_MONTH,31);
              
                  // returning the last date
                  Date endDate=calendarEnd.getTime();
              

              要进行迭代,您应该使用日历对象并增加 day_of_month 变量

              希望对你有帮助

              【讨论】:

              • 啊,我没有意识到你可以在日历和日期之间转换!
              【解决方案15】:

              您可以使用 Jodatime,如本帖 Java Joda Time - Implement a Date range iterator 所示

              此外,您可以使用公历并一次移动一天,如此处所示。 I need a cycle which iterates through dates interval

              PS。建议:先搜索一下。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-04-12
                • 1970-01-01
                • 1970-01-01
                • 2022-12-11
                • 2014-03-02
                • 1970-01-01
                相关资源
                最近更新 更多