【问题标题】:How to get last three months first date and last date based on current date including current date in java?如何根据当前日期(包括java中的当前日期)获取最近三个月的第一个日期和最后一个日期?
【发布时间】:2019-09-15 23:04:18
【问题描述】:

我想根据月份对值进行分类,以便根据当前月份(包括当前月份值)过滤过去三个月的第一个和最后一个日期所需的值。这里有多少最后几个月是参数。我想要所有月份的第一个日期和最后一个日期的列表。任何相同的逻辑都会有所帮助。

例如:-

     //     parameters 
          int lastMonths = 3;
          date currentDate= 26-04-2019;

 //expected output
 current month is 04-2019 ,1st date is 1-04-2019 and last date is 30-04-2019 
 previous month is 03-2019, 1st date is 01-03-2019 and last date is 31-03-2019
 previous month is 02-2019, 1st date is 01-02-2019 and last date is 28-02-2019

【问题讨论】:

    标签: java date calendar localdate


    【解决方案1】:

    如果你需要一个 Date 对象,那么下面的就可以了

            Date date = getDate(targetDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, -3);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
    
            // calendar.getTime()
            // The line above returns Date object
    

    如果你需要一个普通的字符串,那么你可以通过简单地使用 org.joda.time 库中的 DateTimeFormatter 以任何你想要的方式对其进行格式化,然后在 calendar.getTimeInMillis() 上使用它的 print() 方法.

    【讨论】:

    • 这些可怕的类在几年前被 JSR 310 采用的 java.time 类所取代。
    【解决方案2】:

    重要的是 - 有大量的库可以满足您的这种特定需求,但我想依赖一个能够完成这项工作并且实际上是为(您的一些......)这些用例而设计的库 - Java.time.LocalDate 库(已内置于 Java 8)

    import java.time.LocalDate;
    
    LocalDate now = LocalDate.now(); // 2019-04-26
    

    为了获得一个月的第一天和最后一天,您可以使用:

    LocalDate start = YearMonth.now().atDay(1);
    

    (当然现在可以是其他月份)

    LocalDate end = YearMonth.now().atEndOfMonth();
    

    您可以在一两个月内专门使用它,或者使用一些 for 循环。以下示例:
    1.具体调用:

    LocalDate earlierOneMonth = now.minusMonths(1); // 2019-03-26
    earlierOneMonth.getDay(); // 26
    

    2。 For循环:(所以你需要一个数组/列表之类的东西来存储这些值......)

    for(int i=0; i < lastMonths - 1; i++){
       arr(i) = now.minusMonths(i + 1);
    
    }
    

    另外,为了得到月份的名字,你可以使用 ->

    earlierOneMonth.getMonth(); // APRIL
    earlierOneMonth.getMonth.getValue(); // 04
    

    最后,为了得到年份,你可以使用 ->

    earlier.getYear(); // 2019
    

    获得所有所需的值后,您可以按照您的要求将它们打印出来,并获得预期的输出:

     "current month is" + nowMonth + "-" + nowYear + " ,1st date is" +  nowDay + "-" + nowMonth + "-" + nowYear + " and last date is ...
    
    

    让我知道是否足够清楚:)

    【讨论】:

      【解决方案3】:

      使用 java.util.Calendar 进行日期的加减运算

      java.text.DateFormat 格式化日期

          DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
          DateFormat monthFormat = new SimpleDateFormat("MM-yyyy", Locale.US);
          Calendar cal = Calendar.getInstance();
          cal.setTime(format.parse("26-04-2019"));
          for (int i = 0; i < 3; i++){
              System.out.println("currentDate: " + monthFormat.format(cal.getTime())); // print current month
      
              cal.set(Calendar.DAY_OF_MONTH, 1);
              System.out.println("first date: " + format.format(cal.getTime())); // print first date
      
              cal.add(Calendar.MONTH, 1);
              cal.set(Calendar.DAY_OF_MONTH, 1);
              cal.add(Calendar.DATE, -1);
      
              System.out.println("last date: " + format.format(cal.getTime())); // print last date
      
      
              cal.add(Calendar.MONTH, -1);
          }
      

      【讨论】:

      • 这些可怕的类在几年前被 JSR 310 采用后的 java.time 类所取代。建议在 2019 年使用它们是糟糕的建议。
      【解决方案4】:
          int lastMonths = 3;
      
          Calendar calendar = Calendar.getInstance();
      
          int year = calendar.get(Calendar.YEAR);
          int month = calendar.get(Calendar.MONTH) + 1;
          int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
      
          DateFormat monthYearFormat = new SimpleDateFormat("MM-yyyy");
      
          for (int i = 0; i < lastMonths; i++) {
      
              int monthOfYear = month - i;
      
              // if month is january, reset couter and month
              if(monthOfYear == 0) {
                  month = 13;
                  year -= 1;
                  i = 0;
                  continue;
              }
      
              // get last day of month (month length)
              YearMonth yearMonth = YearMonth.of(year, monthOfYear);
              int firstDay = 1;
              int lastDay  = yearMonth.lengthOfMonth();
      
              // create date with given year, month and day
              Date date = new GregorianCalendar(year, monthOfYear - 1, firstDay).getTime();
      
              String monthAndYear = monthYearFormat.format(date);
      
              String currentOrPrevious;
      
              if (i == 0) {
                  currentOrPrevious = "current";
              } else {
                  currentOrPrevious = "previous";
              }
      
              String output = String.format("%s month is %s, 1st date is %02d-%s and last date is %d-%s", currentOrPrevious, monthAndYear, firstDay, monthAndYear, lastDay, monthAndYear);
      
              System.out.println(output);
          }
      

      输出:

      current month is 04-2019, 1st date is 01-04-2019 and last date is 30-04-2019
      previous month is 03-2019, 1st date is 01-03-2019 and last date is 31-03-2019
      previous month is 02-2019, 1st date is 01-02-2019 and last date is 28-02-2019
      

      【讨论】:

      • 随着 JSR 310 的采用,这些可怕的类在几年前被 java.time 所取代。
      【解决方案5】:
          LocalDate currentDate = LocalDate.of(2019, 4, 26);//current date
          System.out.println(currentDate);
          int lastMonths = 3;//number of months
          LocalDate prevDate = null;
          LocalDate start = null;
          LocalDate end = null;
      
          for(int i = 0; i < lastMonths; i++) {
              if(prevDate == null) {
                  start = currentDate.withDayOfMonth(1);//First day of current month
                  end = currentDate.withDayOfMonth(currentDate.lengthOfMonth());//Last day of current month
                  prevDate = currentDate.minusMonths(1);//subtracting one month from current month 
              } else {
                  start = prevDate.withDayOfMonth(1);//First day of previous month
                  end = prevDate.withDayOfMonth(prevDate.lengthOfMonth());//Last day of previous month
                  prevDate = prevDate.minusMonths(1);//subtracting one month from previous month
              }
              System.out.println(start + " " + end);
          }
      

      输出:

      2019-04-26
      2019-04-01 2019-04-30
      2019-03-01 2019-03-31
      2019-02-01 2019-02-28
      

      参考: Get first and last day of month using threeten, LocalDate

      【讨论】:

        【解决方案6】:

        tl;博士

        YearMonth.now().minusMonths( 3 ).atDay( 1 )      // Get the first day of the month of three months ago. Returns `LocalDate` object.
        YearMonth.now().minusMonths( 3 ).atEndOfMonth()  // Get the last day of the month of three months ago. Returns `LocalDate` object.
        

        YearMonth

        你真的很在乎月份。日期是次要的。所以专注于月份。 Java 有一个类!

        YearMonth 类表示特定年份的特定月份。

        ZoneId z = ZoneId.of( "America/Edmonton" ) ;
        YearMonth currentYm = YearMonth.now( z ) ;
        

        收集您感兴趣的月份。

        List< YearMonth > yms = new ArrayList<>() ;
        int limit = 3 ; // We want current month plus three previous months. 
        for( int i = 0 ; i <= limit ; i ++ ) {
            YearMonth ym = currentYm.minusMonths( i ) ;
            yms.add( ym ) ;
        }
        

        当您需要日期时,循环列表。让YearMonth 确定该月的第一天和最后几天。

        for( YearMonth ym : yms ) {
            System.out.println( "YearMonth: " + ym + " starts: " + ym.atDay( 1 ) +  " ends: " + ym.atEndOfMonth() ) ; 
        }
        

        看到这个code run live at IdeOne.com

        年月:2019-04 开始:2019-04-01 结束:2019-04-30

        年月:2019-03 开始​​:2019-03-01 结束:2019-03-31

        年月:2019-02 开始:2019-02-01 结束:2019-02-28

        年月:2019-01 开始:2019-01-01 结束:2019-01-31

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多