如何在Java中获取两个日期之间的月份列表

huangapple go评论72阅读模式
英文:

How to get list of months between two dates in Java

问题

以下是您提供的代码的翻译部分:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {
   public static void main(String[] args) {
       String date1 = "3/17/2020";
       String date2 = "3/17/2021";

    DateFormat formater = new SimpleDateFormat("MM/dd/yyyy");

    Calendar beginCalendar = Calendar.getInstance();
    Calendar finishCalendar = Calendar.getInstance();

    try {
        beginCalendar.setTime(formater.parse(date1));
        finishCalendar.setTime(formater.parse(date2));
    } catch (ParseException e) {
        e.printStackTrace();
    }
  DateFormat formaterYd = new SimpleDateFormat("01-MMM-yyyy");


    while (beginCalendar.before(finishCalendar)) {
        // add one month to date per loop
        String date = formaterYd.format(beginCalendar.getTime()).toUpperCase();
        System.out.println(date);
        beginCalendar.add(Calendar.MONTH, 1);
       }
   }
}

希望这对您有所帮助!如果您有任何问题,请随时问我。

英文:

I am trying to get a list of months (actually the first days of those months) between two dates in Java but I am not getting the expected results.

The start date is "3/17/2020", the end date "3/17/2021" and the expected result is as follows:

"01-Mar-2020"
"01-Apr-2020"
"01-May-2020"
"01-Jun-2020"
"01-Jul-2020"
"01-Aug-2020"
"01-Sep-2020"
"01-Oct-2020"
"01-Nov-2020"
"01-Dec-2020"
"01-Jan-2021"
"01-Feb-2021"
"01-Mar-2021"

Here below is the code I am using:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {
   public static void main(String[] args) {
       String date1 = "3/17/2020";
       String date2 = "3/17/2021";

    DateFormat formater = new SimpleDateFormat("MM/dd/yyyy");

    Calendar beginCalendar = Calendar.getInstance();
    Calendar finishCalendar = Calendar.getInstance();

    try {
        beginCalendar.setTime(formater.parse(date1));
        finishCalendar.setTime(formater.parse(date2));
    } catch (ParseException e) {
        e.printStackTrace();
    }
  DateFormat formaterYd = new SimpleDateFormat("01-MMM-YYYY");


    while (beginCalendar.before(finishCalendar)) {
        // add one month to date per loop
        String date =    formaterYd.format(beginCalendar.getTime()).toUpperCase();
        System.out.println(date);
        beginCalendar.add(Calendar.MONTH, 1);
       }
   }
}

With the above code I am getting the following result:

"01-Jan-2020"
"01-Feb-2020"
"01-Mar-2020"
"01-Apr-2020"
"01-May-2020"
"01-Jun-2020"
"01-Jul-2020"
"01-Aug-2020"
"01-Sep-2020"
"01-Oct-2020"
"01-Nov-2020"
"01-Dec-2020"

Please help me understand the issue and suggest any solution for the same with java 7.

答案1

得分: 7

以下是翻译好的内容:

我建议您使用[现代](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html)的 `java.time` 日期时间 API 和相应的格式化 API(包:`java.time.format`)来完成此操作。您可以从**[教程:日期时间](https://docs.oracle.com/javase/tutorial/datetime/index.html)**中了解有关现代日期时间 API 的更多信息。`java.util` 日期时间 API 和 `SimpleDateFormat` 已过时且容易出错。如果您未使用 Java 8,仍可以通过 [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) 库使用 Java 8 日期时间 API。

如果您在 Android 上进行操作且您的 Android API 级别仍不符合 Java 8可以查看[通过解糖获得的 Java 8+ API](https://developer.android.com/studio/write/java8-support-table)。

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;

    public class Main {
        public static void main(String[] args) {
            // 测试
            System.out.println(getDateList("3/17/2020",  "3/17/2021"));
        }

        static List<String> getDateList(String strStartDate, String strEndDate) {
            // 输入格式化器
            DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/u");

            // 输出格式化器
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MMM-uuuu");

            // 将字符串解析为 LocalDate 实例
            LocalDate startDate = LocalDate.parse(strStartDate, inputFormatter);
            LocalDate endDate = LocalDate.parse(strEndDate, inputFormatter);

            return Stream.iterate(startDate.withDayOfMonth(1), date -> date.plusMonths(1))
                    .limit(ChronoUnit.MONTHS.between(startDate, endDate.plusMonths(1)))
                    .map(date -> date.format(outputFormatter))
                    .collect(Collectors.toList());
        }
    }

**输出:**

    [01-Mar-2020, 01-Apr-2020, 01-May-2020, 01-Jun-2020, 01-Jul-2020, 01-Aug-2020, 01-Sep-2020, 01-Oct-2020, 01-Nov-2020, 01-Dec-2020, 01-Jan-2021, 01-Feb-2021, 01-Mar-2021]

## 使用旧版 API:

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;

    public class Main {
        public static void main(String[] args) throws ParseException {
            // 测试
            System.out.println(getDateList("3/17/2020", "3/17/2021"));
        }

        static List<String> getDateList(String strStartDate, String strEndDate) throws ParseException {
            // 要填充和返回的列表
            List<String> dateList = new ArrayList<>();

            // 输入格式化器
            DateFormat inputFormatter = new SimpleDateFormat("M/d/yyyy");

            // 输出格式化器
            DateFormat outputFormatter = new SimpleDateFormat("dd-MMM-yyyy");

            // 将字符串解析为 Date 实例
            Date startDate = inputFormatter.parse(strStartDate);
            Date endDate = inputFormatter.parse(strEndDate);

            // 起始的日历
            Calendar startWith = Calendar.getInstance();
            startWith.setTime(startDate);
            startWith.set(Calendar.DAY_OF_MONTH, 1);

            for (Calendar calendar = startWith; calendar.getTime().getTime() <= endDate.getTime(); calendar
                    .add(Calendar.MONTH, 1)) {
                dateList.add(outputFormatter.format(calendar.getTime()));
            }

            return dateList;
        }
    }

**输出:**

    [01-Mar-2020, 01-Apr-2020, 01-May-2020, 01-Jun-2020, 01-Jul-2020, 01-Aug-2020, 01-Sep-2020, 01-Oct-2020, 01-Nov-2020, 01-Dec-2020, 01-Jan-2021, 01-Feb-2021, 01-Mar-2021]
英文:

I recommend you do it using the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time. The java.util date-time API and SimpleDateFormat are outdated and error-prone. In case you are not using Java-8, you can still use Java-8 date-time API through ThreeTenABP library.

If you are doing it in Android and your Android API level is still not compliant with Java8, check Java 8+ APIs available through desugaring.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getDateList(&quot;3/17/2020&quot;,  &quot;3/17/2021&quot;));
}
static List&lt;String&gt; getDateList(String strStartDate, String strEndDate) {
// Formatter for the input
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(&quot;M/d/u&quot;);
// Formatter for the output
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(&quot;dd-MMM-uuuu&quot;);
// Parse strings to LocalDate instances
LocalDate startDate = LocalDate.parse(strStartDate, inputFormatter);
LocalDate endDate = LocalDate.parse(strEndDate, inputFormatter);
return Stream.iterate(startDate.withDayOfMonth(1), date -&gt; date.plusMonths(1))
.limit(ChronoUnit.MONTHS.between(startDate, endDate.plusMonths(1)))
.map(date -&gt; date.format(outputFormatter))
.collect(Collectors.toList());
}
}

Output:

[01-Mar-2020, 01-Apr-2020, 01-May-2020, 01-Jun-2020, 01-Jul-2020, 01-Aug-2020, 01-Sep-2020, 01-Oct-2020, 01-Nov-2020, 01-Dec-2020, 01-Jan-2021, 01-Feb-2021, 01-Mar-2021]

Using legacy API:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) throws ParseException {
// Test
System.out.println(getDateList(&quot;3/17/2020&quot;, &quot;3/17/2021&quot;));
}
static List&lt;String&gt; getDateList(String strStartDate, String strEndDate) throws ParseException {
// List to be populated and returned
List&lt;String&gt; dateList = new ArrayList&lt;&gt;();
// Formatter for the input
DateFormat inputFormatter = new SimpleDateFormat(&quot;M/d/yyyy&quot;);
// Formatter for the output
DateFormat outputFormatter = new SimpleDateFormat(&quot;dd-MMM-yyyy&quot;);
// Parse strings to LocalDate instances
Date startDate = inputFormatter.parse(strStartDate);
Date endDate = inputFormatter.parse(strEndDate);
// Calendar to start with
Calendar startWith = Calendar.getInstance();
startWith.setTime(startDate);
startWith.set(Calendar.DAY_OF_MONTH, 1);
for (Calendar calendar = startWith; calendar.getTime().getTime() &lt;= endDate.getTime(); calendar
.add(Calendar.MONTH, 1)) {
dateList.add(outputFormatter.format(calendar.getTime()));
}
return dateList;
}
}

Output:

[01-Mar-2020, 01-Apr-2020, 01-May-2020, 01-Jun-2020, 01-Jul-2020, 01-Aug-2020, 01-Sep-2020, 01-Oct-2020, 01-Nov-2020, 01-Dec-2020, 01-Jan-2021, 01-Feb-2021, 01-Mar-2021]

答案2

得分: 4

**Java7** 解决方案

public static void main(String[] args) throws ParseException {
    DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
    Date dateFrom = df1.parse("3/17/2020");
    Date dateTo = df1.parse("3/17/2021");
    final Locale locale = Locale.US;

    DateFormat df2 = new SimpleDateFormat("MMM-yyyy", Locale.US);
    List<String> months = getListMonths(dateFrom, dateTo, locale, df2);

    for (String month : months)
        System.out.println(month.toUpperCase(locale));
}

public static List<String> getListMonths(Date dateFrom, Date dateTo, Locale locale, DateFormat df) {
    Calendar calendar = Calendar.getInstance(locale);
    calendar.setTime(dateFrom);

    List<String> months = new ArrayList<>();

    while (calendar.getTime().getTime() <= dateTo.getTime()) {
        months.add(df.format(calendar.getTime()));
        calendar.add(Calendar.MONTH, 1);
    }

    return months;
}

**Output:**

MAR-2020
APR-2020
MAY-2020
JUN-2020
JUL-2020
AUG-2020
SEP-2020
OCT-2020
NOV-2020
DEC-2020
JAN-2021
FEB-2021
MAR-2021
英文:

Java7 soulution:

public static void main(String[] args) throws ParseException {
DateFormat df1 = new SimpleDateFormat(&quot;MM/dd/yyyy&quot;, Locale.US);
Date dateFrom = df1.parse(&quot;3/17/2020&quot;);
Date dateTo = df1.parse(&quot;3/17/2021&quot;);
final Locale locale = Locale.US;
DateFormat df2 = new SimpleDateFormat(&quot;MMM-yyyy&quot;, Locale.US);
List&lt;String&gt; months = getListMonths(dateFrom, dateTo, locale, df2);
for (String month : months)
System.out.println(month.toUpperCase(locale));
}
public static List&lt;String&gt; getListMonths(Date dateFrom, Date dateTo, Locale locale, DateFormat df) {
Calendar calendar = Calendar.getInstance(locale);
calendar.setTime(dateFrom);
List&lt;String&gt; months = new ArrayList&lt;&gt;();
while (calendar.getTime().getTime() &lt;= dateTo.getTime()) {
months.add(df.format(calendar.getTime()));
calendar.add(Calendar.MONTH, 1);
}
return months;
}

Output:

MAR-2020
APR-2020
MAY-2020
JUN-2020
JUL-2020
AUG-2020
SEP-2020
OCT-2020
NOV-2020
DEC-2020
JAN-2021
FEB-2021
MAR-2021

答案3

得分: 3

使用 java.time.LocalDate

public static List<LocalDate> diff(LocalDate start, LocalDate end) {
    return start
            .datesUntil(end)
            .filter(e -> e.getDayOfMonth() == 1)
            .collect(Collectors.toList());
}

diff(LocalDate.now(), LocalDate.of(2020, 12, 20))

输出:

[2020-10-01, 2020-11-01, 2020-12-01]

您可以使用 DateTimeFormatter 字符串日期与 LocalDate 相互转换。

编辑
仅使用 Java 7(对问题中的代码进行了修改):

public static void main(String[] args) throws IOException {
    String date1 = "3/17/2020";
    String date2 = "3/17/2021";

    DateFormat formater = new SimpleDateFormat("MM/dd/yyyy");

    Calendar beginCalendar = Calendar.getInstance();
    Calendar finishCalendar = Calendar.getInstance();

    try {
        beginCalendar.setTime(formater.parse(date1));
        finishCalendar.setTime(formater.parse(date2));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    DateFormat formaterYd = new SimpleDateFormat("dd-MMM-YYYY");

    // 注意在 while 中的条件
    while (beginCalendar.compareTo(finishCalendar) <= 0) {
        Calendar tmp = (Calendar)beginCalendar.clone();
        tmp.set(Calendar.DAY_OF_MONTH, 1);
        String date = formaterYd.format(tmp.getTime()).toUpperCase();
        System.out.println(date);
        beginCalendar.add(Calendar.MONTH, 1);
    }
}
英文:

Using java.time.LocalDate:

public static List&lt;LocalDate&gt; diff(LocalDate start, LocalDate end) {
return start
.datesUntil(end)
.filter(e -&gt; e.getDayOfMonth() == 1)
.collect(Collectors.toList());
}
diff(LocalDate.now(), LocalDate.of(2020, 12, 20))

Output:

[2020-10-01, 2020-11-01, 2020-12-01]

You can use DateTimeFormatter string date to LocalDate and vice-versa.

EDIT
Using java 7 only (modified given code in question):

public static void main(String[] args) throws IOException {
String date1 = &quot;3/17/2020&quot;;
String date2 = &quot;3/17/2021&quot;;
DateFormat formater = new SimpleDateFormat(&quot;MM/dd/yyyy&quot;);
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(date1));
finishCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat formaterYd = new SimpleDateFormat(&quot;dd-MMM-YYYY&quot;);
// mind this condition in while
while (beginCalendar.compareTo(finishCalendar) &lt;= 0) {
Calendar tmp = (Calendar)beginCalendar.clone();
tmp.set(Calendar.DAY_OF_MONTH, 1);
String date = formaterYd.format(tmp.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
}
}

huangapple
  • 本文由 发表于 2020年9月17日 15:48:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63933494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定