java 在java中查找两个给定日期之间的所有月份名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12069342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:28:35  来源:igfitidea点击:

Find all month names between two given date in java

java

提问by JDGuide

I need All month/Year names between two given date.I need this out put only on java.

我需要两个给定日期之间的所有月份/年份名称。我只需要将它放在 java 上。

Example :

例子 :

Input Date:

    date 1- 20/12/2011 
    date 2- 22/08/2012

Now ,my expected result should be :- 

        Dec/2011
        Jan/2012
        Feb/2012
        Mar/2012
        Apr/2012
        May/2012
        Jun/2012
        Jul/2012
        Aug/2012

Could anybody help me. Thanks in Advance.

有人能帮我吗。提前致谢。

采纳答案by Eugene

Using Joda-Time (since not specified, I assumeyou could at least have a look at what joda time is):

使用 Joda-Time(由于未指定,我假设您至少可以看看 joda 时间是什么):

 LocalDate date1 = new LocalDate("2011-12-12");
 LocalDate date2 = new LocalDate("2012-11-11"); 
 while(date1.isBefore(date2)){
     System.out.println(date1.toString("MMM/yyyy"));
     date1 = date1.plus(Period.months(1));
 }

回答by Denys Séguret

You can simply use the Calendar classand iterate from one date to the other one by adding a month at each iteration using myCalendar.add(Calendar.MONTH, 1);.

您可以简单地使用Calendar 类并通过在每次迭代中添加一个月来从一个日期迭代到另一个日期using myCalendar.add(Calendar.MONTH, 1);

The Calendar class takes care of avoiding overflows and updating the other fields (here the year) for you.

Calendar 类负责避免溢出并为您更新其他字段(此处为年份)。

回答by Ole V.V.

java.time.YearMonth

java.time.YearMonth

While the other answers were good answers when written, they are now outdated. Since Java 8 introduced the YearMonthclass, this task has been greatly simplified:

虽然其他答案在写作时是很好的答案,但它们现在已经过时了。自从 Java 8 引入了这个YearMonth类,这个任务已经大大简化了:

    String date1 = "20/12/2011";
    String date2 = "22/08/2012";

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ROOT);
    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM/uuuu", Locale.ROOT);
    YearMonth endMonth = YearMonth.parse(date2, dateFormatter);
    for (YearMonth month = YearMonth.parse(date1, dateFormatter);
            ! month.isAfter(endMonth);
            month = month.plusMonths(1)) {
        System.out.println(month.format(monthFormatter));
    }

This prints:

这打印:

Dec/2011
Jan/2012
Feb/2012
Mar/2012
Apr/2012
May/2012
Jun/2012
Jul/2012
Aug/2012

Please supply an appropriate locale for the second call to DateTimeFormatter.ofPattern()to get the month names in your language. And the first call too to be on the safe side.

请为第二次调用提供适当的语言环境,DateTimeFormatter.ofPattern()以获取您语言中的月份名称。第一次打电话也是为了安全起见。

回答by Dan

Per conversation above. Use Calendar and the add method.

根据上面的对话。使用 Calendar 和 add 方法。

I've not tested this but it's about there:

我没有测试过这个,但它就在那里:

public static List<Date> datesBetween(Date d1, Date d2) {
    List<Date> ret = new ArrayList<Date>();
    Calendar c = Calendar.getInstance();
    c.setTime(d1);
    while (c.getTimeInMillis()<d2.getTime()) {
        c.add(Calendar.MONTH, 1);
        ret.add(c.getTime());
    }
    return ret;
}

回答by Uchenna Nwanyanwu

Do this

做这个

 Calendar cal = Calendar.getInstance();
 cal.setTime(your_date_object);
 cal.add(Calendar.MONTH, 1);

回答by Kushal Jain

So suppose you have these two date. And you can compare it easily by iterating an while loop till fromDate is before toDate.

所以假设你有这两个约会。您可以通过迭代 while 循环直到 fromDate 在 toDate 之前轻松比较它。

Date fromDate= new Date("1/4/2016");
Date toDate = new Date("31/12/2016");

int i=0;
while(fromDate.before(toDate)){
    i=i+1;
    fromDate.setMonth(i);
    System.out.println(fromDate);
}

You can add date in list or do whatever do want to do!!!

您可以在列表中添加日期或做任何想做的事情!!!

回答by Basil Bourque

java.time

时间

The modern approach uses the java.timeclasses. Never use Date/Calendar/SimpleDateFormatand such.

现代方法使用java.time类。永远不要使用Date/ Calendar/ 之SimpleDateFormat类的。

LocalDate

LocalDate

The LocalDateclass represents a date-only value, without time-of-day and without time zone.

LocalDate级表示日期,只值,没有时间的天,没有时区。

LocalDate startLocalDate = LocalDate.of( 2011 , Month.DECEMBER , 20 ) ;  
LocalDate stopLocalDate = LocalDate.of( 2012 , Month.AUGUST , 2 ) ;

YearMonth

YearMonth

When interested only in the year and month, use the class YearMonth.

如果只对年和月感兴趣,请使用类YearMonth

YearMonth start = YearMonth.from( startLocalDate) ;
YearMonth stop = YearMonth.from( stopLocalDate ) ;

Loop.

环形。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM/uuuu" , Locale.US ) ;
int initialCapacity = start.until( stop , ChronoUnit.MONTHS ) ;
List< YearMonth > yearMonths = new ArrayList<>( initialCapacity ) ;
YearMonth ym = start ;
while ( ym.isBefore( stop ) ) {
    System.out.println( ym.format( f ) ) ;  // Output your desired text.
    yearMonths.add( ym ) ;
    ym = ym.plusMonths( 1 ) ;  // Increment to set up next loop.
}


About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多