1
votes

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

2
calc = Calendar.getInstance(); calc.add(Calendar.YEAR, -18); calc.add(Calendar.DATE, -1); Date date = calc.getTime(); System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(date)");MadProgrammer
If at all possible, you should be take advantage of either Java 8's new Time API or Joda-Time, they are generally easier and less messy then CalendarMadProgrammer
@MadProgrammer the above code will work but in corner cases like 1st of the month this will not workMUHAMMED SHAMEER
Should do, do you have an example where it doesn'tMadProgrammer
In birthdate age confirmation. i need to register user above 18 years of age.MUHAMMED SHAMEER

2 Answers

5
votes

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
1
votes

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