11

I need All month/Year names between two given date.I need this out put only on 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.

JDGuide
  • 6,239
  • 12
  • 46
  • 64

7 Answers7

12

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

 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));
 }
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Thank you mate.I knew Joda-Time.But, my first priority is to do this without any third party use. Let me try with my own java code, if failure then , i will use Joda-Time. – JDGuide Aug 22 '12 at 09:14
  • 1
    @JDeveloper no problem! Eventually you will probably use only Joda-Time because it's superior to the standard libraries. There were a high number of votes to include Joda in JDK 7, but it did not happen. :( ThankYou==upvote on SO :) – Eugene Aug 22 '12 at 09:16
  • FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Sep 21 '18 at 03:44
10

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

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Will you please provide the code.It will be very helpful to me. – JDGuide Aug 22 '12 at 08:48
  • I'm reluctant to write myself the complete code at this looks too much like a homework or online interview problem. And that would make the question/answer more specific than needed. Can you precise what you find hard from there ? – Denys Séguret Aug 22 '12 at 08:49
  • 2
    I think you should work it out. It's not that hard. And your name is JDeveloper! – Dan Aug 22 '12 at 08:49
  • You are right @Dan Matthews-Grout.I am trying before 1 hour but, not solved.So, i posted this for Java Master's support. – JDGuide Aug 22 '12 at 08:54
  • Give me a minute to start my vm – Dan Aug 22 '12 at 08:56
  • Read the javadoc I linked too. Find how to initialize your myCalendar instance from the first date. Write your loop (see how to test the calendar isn't past the other date). Print results during iteration. – Denys Séguret Aug 22 '12 at 08:57
  • Oh, sure. I am trying here. You please try. – JDGuide Aug 22 '12 at 08:57
  • 1
    @JDeveloper the good practice on SO is to not write the complete or exact solution in such a case but give hints. We don't want SO to be a "Do my homework" site. I'm sure you can write it from the walkthrough I gave. – Denys Séguret Aug 22 '12 at 08:59
  • Compromise here that it isn't exactly what he wants but should so the methodology. – Dan Aug 22 '12 at 09:00
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Sep 21 '18 at 03:44
5

java.time.YearMonth

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

    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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
4

Per conversation above. Use Calendar and the add method.

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;
}
Dan
  • 1,030
  • 5
  • 12
  • I really don't think you should give the complete solution to a homework question. – Denys Séguret Aug 22 '12 at 09:00
  • It's not - he still needs to deal with String input and output ;) He asked for a code example to walk through. Personally I find that helpful as I can work backwards to see how it was achieved. Taking a puritan stance on "no complete" answers is a bit counter-productive to the aims of the site. Plus I've not tested it, so it could have (probably not) bugs. – Dan Aug 22 '12 at 09:02
1

Do this

 Calendar cal = Calendar.getInstance();
 cal.setTime(your_date_object);
 cal.add(Calendar.MONTH, 1);
Uchenna Nwanyanwu
  • 3,174
  • 3
  • 35
  • 59
0

So suppose you have these two date. And you can compare it easily by iterating an while loop till fromDate is before 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!!!

Kushal Jain
  • 3,029
  • 5
  • 31
  • 48
0

java.time

The modern approach uses the java.time classes. Never use Date/Calendar/SimpleDateFormat and such.

LocalDate

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

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

YearMonth

When interested only in the year and month, use the class 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

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

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project 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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154