如何在 Java 中设置日期范围的格式?
我有两个日期——开始和结束。我想对它们进行格式化,以便如果月份匹配,它们会折叠为“20-23 AUG”之类的内容,并且如果它们在月底突破,例如“20 SEP - 1 OCT”,格式仍然正确。是否有任何库可以实现此目的,或者我是否必须编写代码规则来使用单独的 DateFormats 显示日期范围?
I have two dates - a start and an end. I'd like to format them so that if the months match, they collapse to something like "20-23 AUG" and still format correctly if they break over the end of the month, like "20 SEP - 1 OCT". Are there any libraries out there for accomplishing this, or would I have to hand code rules for displaying ranges of dates using individual DateFormats?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个使用 JodaTime 的解决方案,它是 Java 中处理日期的最佳库(上次我检查过)。格式化很简单,并且毫无疑问可以通过使用自定义 DateFormatter 实现来改进。这还检查年份是否相同,但不输出年份,这可能会令人困惑。
产出:
8月23日至25日
8月23日至9月5日
Here's a solution using JodaTime, the best library for dealing with dates in Java (last time I checked). The formatting is simple and could no doubt be improved by using custom DateFormatter implementations. This also checks that the year is the same, but doesn't output the year, which could be confusing.
Output:
23 - 25 Aug
23 Aug - 5 Sep
我对其他答案感到失望。 Joda 时间在 GWT 中不起作用,SimpleDateFormat 也不起作用。不管怎样,我已经了解了 GWT 中的 DateTimeFormat。主要问题是日期对象 getMonth() 函数已被弃用,并且似乎没有一个好的方法来比较月份和/或年份。该解决方案不包括年份检查(可以通过更改 MonthFormatter 轻松添加),但这对我的情况并不重要。
I was disappointed with the other answers. Joda time didn't work in GWT and neither does SimpleDateFormat. Anyway, I already knew about DateTimeFormat in GWT. The main issue is that date objects getMonth() function is deprecated, and there doesn't seem to be a good way to compare months and/or years. This solution doesn't include year checking (which could be easily added by changing the monthFormatter), but that's not important for my case.
查看 java 的 SimpleDateFormat 类。您可以构造一个 SimpleDateFormat 将日期模式作为字符串传递。
Checkout java's SimpleDateFormat class. You can construct a SimpleDateFormat passing you're date pattern as a String.
为了添加 Jeroen 的答案,您将使用 SimpleDateFormat 两次,一次用于范围的每一端。
To add to Jeroen's answer, you're going to use SimpleDateFormat twice, once for each end of the range.
默认情况下,Java 中没有日期范围这样的类型,因此没有任何 DateFormats 不适用于这种情况的字符串表示形式。
我认为最好的方法是创建 TimeSpan 或 TimeDiff 类型并将方法重写为字符串。或者,正如您建议的,如果您还需要两个解析,则创建一个 DateFormmater 。
There is not such type as day range in Java by default, so none of the DateFormats apply to string representation of this case.
The best in my opinion, well be creation of type TimeSpan or TimeDiff and override method to string. Or as You suggested create a DateFormmater if you need two also parsing.