java.time.Period ,划分周期给出错误的结果 [英] java.time.Period , dividing the period gives wrong results

查看:59
本文介绍了java.time.Period ,划分周期给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用java.time.Period,结果与我手动计算的结果相差三天.奇怪的是,当我将时间段分成两个时间段时,结果与我手动计算的结果相符.

I tried using java.time.Period, and the results were different from my manual calculations by three days. The weird thing here is when I divide the period into two periods, the results matches my manual calculations.

第二种方法就像我手动计算周期一样.

The second method is just like how I calculate the period manually.

有什么我遗漏的吗?是否有日历算术的标准方法或算法?java.time.Period 使用的算法是什么?

Is there something I have missed? Is there a standard method or algorithm of calendar arithmetic? And what's the algorithm used by java.time.Period ?

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class test2 {

    public static void main(String[] args) {

        LocalDate d1 = LocalDate.of(2014, 2, 14);
        LocalDate d2 = LocalDate.of(2017, 8, 1);

        Period p = Period.between(d1, d2);

        //using period between the two dates directly
        System.out.println("period between " + d1.toString() + " and " + d2.toString() + " is " + p.getYears()
                + " years " + p.getMonths() + " months " + p.getDays() + " Days");

        //dividing the period into two parts 
        p = Period.between(LocalDate.of(2014, 3, 1), d2);

        System.out
                .println("period between " + d1.toString() + " and " + d2.toString() + " is " + p.getYears() + " years "
                        + p.getMonths() + " months " + d1.until(LocalDate.of(2014, 3, 1), ChronoUnit.DAYS) + " Days");

    }
}

推荐答案

您在这里执行两个不同的操作:

You perform two different operations here:

Period p = Period.between(d1, d2)

为您提供了一种格式良好的方式来输出这些日期之间的差异(您已正确使用格式选项).

gives you a nicely formated way to output the difference between these dates (you have used the formatting options correctly).

d1.until(d2, ChronoUnit.DAYS) 

会给你相同的 - 但不是那么好的格式(基本上它只是给你 LocalDates 之间的天数).

will give you the same - but not so nicely formated (basically it just gives you the number of days between the LocalDates).

这篇关于java.time.Period ,划分周期给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆