获取 Java 中自纪元以来的天数、周数和月数
我正在尝试获取自 Java 纪元以来的天数、周数、月数。
Java Calendar 类提供了诸如calendar.get(GregorianCalendar.DAY_OF_YEAR) 或Calendar.get(GregorianCalendar.WEEK_OF_YEAR) 之类的功能,这是一个好的开始,但它并不能完全满足我的需要。
Java 有没有一种优雅的方法来做到这一点?
I'm trying to get the number of days, weeks, months since Epoch in Java.
The Java Calendar class offers things like calendar.get(GregorianCalendar.DAY_OF_YEAR), or Calendar.get(GregorianCalendar.WEEK_OF_YEAR), which is a good start but it doesn't do exactly what I need.
Is there an elegant way to do this in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
java.time
使用 Java 8 及更高版本中内置的 java.time 类。
输出
java.time
Use the java.time classes built into Java 8 and later.
Output
您可以使用 Joda Time 库 轻松完成此操作 - 我随时使用它除了使用标准 Java Date 和 Calendar 类之外的其他相关内容。使用该库看一下下面的示例:
当我运行它时,我得到以下输出:
You can use the Joda Time library to do this pretty easily - I use it for anything time related other than using the standard Java Date and Calendar classes. Take a look at the example below using the library:
When I run this I get the following output:
让我有点惊讶的是,几乎所有答案实际上都是在计算
epoch
和now
之间的天数。使用 java.time.LocalDate 就这么简单:I'm kind of surprised that almost all answers are actually calculating days between
epoch
andnow
. Withjava.time.LocalDate
it's as simple as:或者
or
我不希望有一种优雅的方式来做到这一点,因为这不是一个很常见的要求。我忍不住想知道你为什么要这样做......
但无论如何,我这样做的方法是从
Calendar
中减去纪元日期,然后获取你想要的字段:I wouldn't expect there to be an elegant way of doing it since it is not a very common requirement. I can't help but wonder why you want to do it...
But anyway, the way I would do it is to subtract the epoch date from the
Calendar
and then get the fields you want:Date.getTime( )
- 返回此 Date 对象表示的自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数。您可以使用它以及您关心的时间间隔中有多少毫秒的知识来进行计算。
Date.getTime()
- Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.You can use this and knowledge of how many milliseconds are in the intervals you care about to do the calculations.