月份差 java,Java中月份中两个日期之间的差异

Query regarding calculate months but with some conditions.

with Joda Date-time or date util.

Start Date : 01/01/2018

End Date : 31/12/2020

Total Period difference between above date: 36 months and 0 days

so total month =36

Start Date : 01/01/2018

End Date : 02/01/2021

Total Period difference between above date: 36 months and 2 days.

if there are days remaining then it consider single month.

so total month 36+1= 37

Date issueDate1=03/06/2017;

Date dateTo1=02/06/2020;

int investmentPeriod = Months.monthsBetween(issueDate1, dateTo1).getMonths();

By joda above months are coming 35 which is wrong.

Date start=23/06/2017;

Date end=06/07/2017;

here difference less than a month . so it consider as single month.

解决方案

ZoneId defaultZoneId = ZoneId.systemDefault();

String issueDate1="01/01/2017";

Date issueDate2=new SimpleDateFormat("dd/MM/yyyy").parse(issueDate1);

String dateTo1="31/12/2018";

Date dateTo2=new SimpleDateFormat("dd/MM/yyyy").parse(dateTo1);

here year month days can find easily.This giving ans of all question.

Instant instant = issueDate2.toInstant();

LocalDate localDatestart = instant.atZone(defaultZoneId).toLocalDate();

Instant instant1 = dateTo2.toInstant();

LocalDate localDateend = instant1.atZone(defaultZoneId).toLocalDate().plusDays(1);

Period diff = Period.between(localDatestart, localDateend);

System.out.printf("\nDifference is %d years, %d months and %d days old\n\n",

diff.getYears(), diff.getMonths(), diff.getDays());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值