在 Java 中表示时间段的最佳方式是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6152703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:34:38  来源:igfitidea点击:

What's the best way to represent a time period in Java?

javadate

提问by Joaquín L. Robles

What's the best way to represent a time period in Java? May I use 2 Date objects or is there a better way?

在 Java 中表示时间段的最佳方式是什么?我可以使用 2 个 Date 对象还是有更好的方法?

I.e. all April, the hole 3rd week of July, from January to March, etc.

即整个四月,七月的第三周,一月到三月,等等。

采纳答案by Waldheinz

Here is the usual link to Joda when in comes to time + Java:

以下是有关时间 + Java 的 Joda 的常用链接:

http://joda-time.sourceforge.net/api-release/org/joda/time/Period.html

http://joda-time.sourceforge.net/api-release/org/joda/time/Period.html

Edit: The relevant link for this specific question is http://joda-time.sourceforge.net/api-release/org/joda/time/Interval.html

编辑:这个特定问题的相关链接是http://joda-time.sourceforge.net/api-release/org/joda/time/Interval.html

回答by Orkun Ozen

I see the answers are quite old.

我看到答案很旧。

As of Java 8, we can use the native Java.Timewhich is partially based on Joda Timeand makes the manipulations on dates very easy.

截至Java 8,我们可以使用Java.Time部分基于的本机Joda Time并使对日期的操作变得非常容易。

Take a look at Period, Durationand LocalDateon

看看PeriodDurationLocalDate

回答by Aaron Digulla

Joda Timesolves all your date/time troubles. It has a data range type.

Joda Time解决您所有的日期/时间问题。它有一个数据范围类型。

回答by DNA

If you want to avoid using Joda for some reason, then writing a class that wraps a pair of dates (or the underlying Long values) would be OK, but you'll need to write any methods you need for comparing ranges or determining if a date falls within a range, etc.

如果您出于某种原因想避免使用 Joda,那么编写一个包装一对日期(或底层 Long 值)的类就可以了,但是您需要编写任何您需要的方法来比较范围或确定日期在一个范围内等。

回答by RMT

If you need to use 2 different dates, use 2 different dates and use SimpleDateFormat. Its very simple to use.

如果您需要使用 2 个不同的日期,请使用 2 个不同的日期并使用 SimpleDateFormat。它的使用非常简单。

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.parse(new Date());

回答by Jonny Schubert

If I understand what you want. You could simply use two timestamps. Alternative one timestamp and the period time.

如果我明白你想要什么。您可以简单地使用两个时间戳。另一种时间戳和周期时间。