MUHAMMED SHAMEER
MUHAMMED SHAMEER

Reputation: 59

Getting 18 years before date from calender

I need to get complete date(dd/mm/yyyy) which is 18 years from now. i used code as Calendar calc = Calendar.getInstance(); calc.add(Calendar.YEAR, -18); which retrives 18 years before year not month or date. I need one day 18 years before current date even in corner cases like 1st of any month also. Example 1-06-2015 is current date should get 31-05-1997.To be noted i need code in java6

Upvotes: 4

Views: 6245

Answers (2)

Heath Malmstrom
Heath Malmstrom

Reputation: 80

I would recommend using Joda Time, as it will make date manipulation and math very easy. For example:

DateTime futureDate = new DateTime();
futureDate.minusYears(18).minusDays(1);
futureDate.toDate(); // return a regular Date object

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347204

In Java, a date value is just the number of milliseconds from some fixed point in time, the related classes don't carry a format of their own which you can change, this is what date/time formatters are for

Calendar

From your example, you're basically ignoring the fact that changing any of the Calendar's fields, will effect all the others, for example...

Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.JUNE, 01); // Comment this out for today...
cal.add(Calendar.YEAR, -18);
cal.add(Calendar.DATE, -1);
Date date = cal.getTime();
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(date));

Which outputs

31/05/1997

I would, however, recommend using either Java 8's new Time API or Joda-Time

Java 8 Time API

LocalDate ld = LocalDate.now();
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy").format(ld));

Which outputs

26/06/1997

Edge case...

LocalDate ld = LocalDate.of(2015, Month.JUNE, 1);
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy").format(ld));

Which outputs

31/05/1997

JodaTime

LocalDate ld = new LocalDate();
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormat.forPattern("dd/MM/yyyy").print(ld));

Which outputs

26/06/1997

Edge case...

LocalDate ld = new LocalDate(2015, DateTimeConstants.JUNE, 1);
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormat.forPattern("dd/MM/yyyy").print(ld));

Which outputs

31/05/1997

Upvotes: 9

Related Questions