i need to add a decimal amount of month to a java date : -> i can use this code with joda time api to add a natural amount of months to a date. But how can i add a decimal amount of month ( for example 3.5) to a date ?
Date date = new Date();
DateTime dateTime = new DateTime(date);
dateTime = dateTime.plusMonths(3);
Date newDate = dateTime.toDate();
This will give you an approximation. It's the best you can get.
long oneMonthInNanos = ChronoUnit.MONTHS.getDuration().toNanos();
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Phnom_Penh"));
System.out.println("Now " + now);
System.out.println("In 3.5 months " + now.plusNanos(Math.round(3.5 * oneMonthInNanos)));
System.out.println("In 4.5 months " + now.plusNanos(Math.round(4.5 * oneMonthInNanos)));
System.out.println("In 12 months " + now.plusNanos(Math.round(12.0 * oneMonthInNanos)));
Output when I ran the code just now, was:
Now 2018-11-06T22:31:36.460573+07:00[Asia/Phnom_Penh] In 3.5 months 2019-02-21T11:13:27.460573+07:00[Asia/Phnom_Penh] In 4.5 months 2019-03-23T21:42:33.460573+07:00[Asia/Phnom_Penh] In 12 months 2019-11-07T04:20:48.460573+07:00[Asia/Phnom_Penh]
As has been said in comments, there is no really good definition of a fractional number of months. When you compare the first and the last date-time you also clearly see that 12 months don't add up to a year precisely, though pretty close. Please check yourself whether the results are good enough for your purpose.
I am using java.time. I din't know whether something similar is possible in Joda-Time.
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.