如何在Java中基于当前日期(包括当前日期)获取最近三个月的第一个日期和最后一个日期?

时间:2019-04-26 12:19:07

标签: java date calendar localdate

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

例如:-

     //     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

6 个答案:

答案 0 :(得分:1)

重要的是-有很多库可以满足您这种特定需求,但是我想依靠一个能够完成工作并且实际上是为(在某些情况下)这些用例设计的库- 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(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 ...

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

答案 1 :(得分:1)

  

使用 java.util.Calendar 进行日期的添加和替换

  

java.text.DateFormat 设置日期格式

dec cx

答案 2 :(得分:0)

如果您需要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()方法。

答案 3 :(得分:0)

    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

答案 4 :(得分:0)

    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

答案 5 :(得分:0)

tl; dr

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年1月开始:2019年1月1日结束:2019年1月31日