简体   繁体   English

Java - 我如何将日期作为输入并能够添加/减去其天/月/年

[英]Java - how do I take date as input and be able to add/subtract its days/months/years

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(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();
}

You can convert Date to LocalDate.您可以将日期转换为本地日期。 Its has plus methods, like plusYears(),plusMonths(),plusDays().它有 plus 方法,例如 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);
    }

java.time java.time

Never use the legacy classes Date and SimpleDateFormat .永远不要使用旧类DateSimpleDateFormat Use only java.time classes.仅使用java.time类。

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

To add and subtract, call the plus… and minus… methods.要加减,请调用plus…minus…方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM