Home > OS >  Java - how do I take date as input and be able to add/subtract its days/months/years
Java - how do I take date as input and be able to add/subtract its days/months/years

Time:11-21

I'm currently using this code and I don't know if there is a way to add or subtract the date that I input with Scanner(System.in)

Scanner scanner = new Scanner(System.in);
System.out.println("Date: ");
String date = scanner.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date2=null;
try {
    date2 = dateFormat.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
}

CodePudding user response:

You can convert Date to LocalDate. Its has plus methods, like plusYears(),plusMonths(),plusDays().

    // Date -> LocalDate
    private static LocalDate of(Date date) {
        Instant instant = date.toInstant();
        return instant.atZone(ZoneId.systemDefault()).toLocalDate();
    }
 
    // LocalDate -> Date
    private static Date of(LocalDate localDate) {
        Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

CodePudding user response:

java.time

Never use the legacy classes Date and SimpleDateFormat. Use only java.time classes.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

To add and subtract, call the plus… and minus… methods.

LocalDate later = ld.plusDays( 3 ) ;
LocalDate earlier = ld.minusYears( 7 ) ;
  • Related