Java日期和时间:如何使plus()和直到()彼此相反 [英] Java Date and Time: How do I make plus() and until() to be each others inverse

查看:122
本文介绍了Java日期和时间:如何使plus()和直到()彼此相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,这两种方法彼此相反:

Most of the time, these 2 methods are each others inverse:

  • Temporal Temporal.plus(long, TemporalUnit)
  • long Temporal.until(Temporal, TemporalUnit)
  • Temporal Temporal.plus(long, TemporalUnit)
  • long Temporal.until(Temporal, TemporalUnit)

例如,从1月1日开始

System.out.println("1-JAN plus 1 month: " +
    LocalDate.of(2017, 1, 1).plus(1, ChronoUnit.MONTHS));
System.out.println("1-JAN until 1-FEB in months: " +
    LocalDate.of(2017, 1, 1).until(LocalDate.of(2017, 2, 1), ChronoUnit.MONTHS));

它们彼此相反:

1月1日加上1个月:2017-02-1
1月1日至1月2日:1//良好

1-JAN plus 1 month: 2017-02-01
1-JAN until 1-FEB in months: 1 // GOOD


但是,在此示例中,从1月31日开始:


However, in this example starting from 31-JAN:

System.out.println("31-JAN plus 1 month: " +
    LocalDate.of(2017, 1, 31).plus(1, ChronoUnit.MONTHS));
System.out.println("31-JAN until 28-FEB in months: " +
    LocalDate.of(2017, 1, 31).until(LocalDate.of(2017, 2, 28), ChronoUnit.MONTHS));

它们彼此相反:

31年1月31日加上1个月:2017年2月28日//不好?应该到3月1日吗?
1月31日至2月28日2月:0//还是不好?应该是1?

31-JAN plus 1 month: 2017-02-28 // Bad? Should ceil to 1 March?
31-JAN until 28-FEB in months: 0 // Or is this bad? Should be 1?


如何使它们彼此相反?


How can I make them to be each others inverse?

推荐答案

这些日期之间只有28天,因此整月数为0.但是,如果您希望少于1个月,可以使用一些舍入被认为是一个月.例如

There is only 28 days between those dates so the number of whole months is 0. However you could use a bit of rounding if you want less than 1 month be be considered a month. e.g.

// compare the months after rounding to the next month
LocalDate a = LocalDate.of(2017, 1, 31);
LocalDate b = LocalDate.of(2017, 2, 28);
long months = a.plus(1, ChronoUnit.MONTHS)
        .until(b.plus(1, ChronoUnit.MONTHS), ChronoUnit.MONTHS);
System.out.println(a + " until " + b + " in months: " + months);

打印

2017-01-31 until 2017-02-28 in months: 1

// compare the months after rounding to the next month
LocalDate a = LocalDate.of(2017, 1, 31);
LocalDate b = LocalDate.of(2017, 3, 30);
long months = a.plus(1, ChronoUnit.MONTHS)
        .until(b.plus(1, ChronoUnit.MONTHS), ChronoUnit.MONTHS);
System.out.println(a + " until " + b + " in months: " + months);

打印

2017-01-31 until 2017-03-30 in months: 2

我可能希望加号不加限制

I probably want the plus to ceil instead of to floor

根据您的要求,您可能希望将整个月视为30天.

You might want to treat all months as notionally 30 days depending on your requirements.

这篇关于Java日期和时间:如何使plus()和直到()彼此相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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