简体   繁体   中英

How to add a `Period` to `java.util.Date`?

I have a predefined set of classes, which uses java.util.Date (which cannot be altered) and the requirement is to add a specific period to a date object.

I came across how this can be done using java.time.Period and java.time.LocalDate , but could not find anything to do with java.util.Date .

.....

Date baseDate = sdf.parse("2015-01-01 20:00");
Period twoMonthsAndFiveDays = Period.ofMonths(2).plusDays(5);

//ideal result would be a Date object with value "2015-03-06 20:00"
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm");

    // The given data
    String dateTimeString = "2015-01-01 20:00";
    Period twoMonthsAndFiveDays = Period.ofMonths(2).plusDays(5);

    ZonedDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter)
            .atZone(ZoneId.systemDefault());
    Instant newTime = dateTime.plus(twoMonthsAndFiveDays)
            .toInstant();
    Date oldfashionedDateObject = Date.from(newTime);

    System.out.println(oldfashionedDateObject);

I set my time zone to Asia/Colombo, ran this snippet and got:

Fri Mar 06 20:00:00 IST 2015

If you need to start from a Date that comes from your predefined legacy classes:

    // The given data
    Date originalDate = getDateFromLegacyApi();
    Period twoMonthsAndFiveDays = Period.ofMonths(2).plusDays(5);

    Instant newTime = originalDate.toInstant()
            .atZone(ZoneId.systemDefault())
            .plus(twoMonthsAndFiveDays)
            .toInstant();
    Date oldfashionedDateObject = Date.from(newTime);

So the conversions are

java.util.Date <--> Instant <--> ZonedDateTime

A ZonedDateTime knows how to add a Period . Do the conversions to and from Date only when you need to for interoperability with you legacy classes.

Since you you already know how to use Period on a LocalDate object, then you only need to worry about how to convert java.util.Date to java.time.LocalDate

// converting java.util.Date to java.time.LocalDate
Date today = new Date(); //<--your date to be converted/transformed
Instant instant = Instant.ofEpochMilli(today.getTime());
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDate localDate = localDateTime.toLocalDate();

Taken from: https://javarevisited.blogspot.com/2016/10/how-to-convert-javautildate-to-LocalDate-java8.html#ixzz63z8Djytf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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