Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 329
MUHAMMED SHAMEER Avatar asked Oct 15 '25 17:10

MUHAMMED SHAMEER


1 Answers

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
like image 79
MadProgrammer Avatar answered Oct 18 '25 06:10

MadProgrammer