Reputation: 6525
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.
Upvotes: 10
Views: 15555
Reputation: 86282
java.time.YearMonth
While the older 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.
See the answer by Arvind Kumar Avinash for a solution that better separates model (YearMonth
objects) and user interface (strings to be output) and for a bit more of explanation.
Upvotes: 9
Reputation: 79075
java.time
The existing answers are correct. This answer aims to inform about the state of Joda-Time API and solve the question differently.
In March 2014, Java 8 introduced java.time
, the modern date-time API. Since then, it's been recommended to switch from the legacy date-time API from the standard library (i.e. java.util
date-time API) and the Joda-Time to java.time
API. Shown below is a notice on the Joda-Time Home Page:
Note that from Java SE 8 onwards, users are asked to migrate to
java.time
(JSR-310) - a core part of the JDK which replaces this project.
Steps used in this answer:
LocalDate
instances by using a DateTimeFormatter
with the dd/MM/uuuu
pattern.YearMonth
instances from the above LocalDate
instances.YearMonth
s to a List<YearMonth
> by navigating from the start to end.DateTimeFormatter
with the desired format (e.g. MMM/uuuu
).Demo:
public class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/uuuu");
LocalDate date1 = LocalDate.parse("20/12/2011", parser);
LocalDate date2 = LocalDate.parse("22/08/2012", parser);
YearMonth start = YearMonth.from(date1);
YearMonth end = YearMonth.from(date2);
List<YearMonth> list = new ArrayList<>();
// Create a list of desired YearMonth
for (YearMonth ym = start; !ym.isAfter(end); ym = ym.plusMonths(1))
list.add(YearMonth.from(ym));
System.out.println(list);
// In case you need a list of YearMonth in a different string representation
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM/uuuu", Locale.ENGLISH);
// The following line of code will run only from Java 16 onwards:
// List<String> formattedStrList1 = list.stream()
// .map(ym -> ym.format(formatter))
// .toList();
//
// In case you are using a version lower than Java 16:
List<String> formattedStrList2 = list.stream()
.map(ym -> ym.format(formatter))
.collect(Collectors.toList());
System.out.println(formattedStrList2);
}
}
Output:
[2011-12, 2012-01, 2012-02, 2012-03, 2012-04, 2012-05, 2012-06, 2012-07, 2012-08]
[Dec/2011, Jan/2012, Feb/2012, Mar/2012, Apr/2012, May/2012, Jun/2012, Jul/2012, Aug/2012]
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 3
Reputation: 338516
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.
}
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.
Upvotes: 0
Reputation: 3186
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!!!
Upvotes: 0
Reputation: 120848
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));
}
Upvotes: 12
Reputation: 3204
Do this
Calendar cal = Calendar.getInstance();
cal.setTime(your_date_object);
cal.add(Calendar.MONTH, 1);
Upvotes: 1
Reputation: 1018
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;
}
Upvotes: 4
Reputation: 382130
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.
Upvotes: 10