Getting 18 years before date from calender

前端 未结 2 1736
挽巷
挽巷 2021-01-23 07:01

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

相关标签:
2条回答
  • 2021-01-23 07:33

    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
    
    0 讨论(0)
  • 2021-01-23 07:40

    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
    
    0 讨论(0)
提交回复
热议问题