Java中的日期运算?
我想获取 Date
对象的年/月/日值,但是 docs 说 getYear()
等方法已被弃用。它建议使用 日历
< /a> 相反,但我想知道是否可以使用已弃用的方法来代替?这只是一个用 Processing 编写的玩具程序,但我将在几个对象上进行大量的日期操作,所以速度可能是一个问题。
I want to get the year/month/day values of a Date
object, but the docs say the getYear()
, etc. methods are deprecated. It suggests to use Calendar
instead, but I was wondering if it's okay to use the deprecated methods instead? It's just a toy program written in Processing, but I'll be doing quite a bit of Date operations on several objects, so speed might be a concern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议您查看 Yoda Time,在我看来,这是一个更好的用于日期/时间任务的库。
http://joda-time.sourceforge.net/
I would suggest you look at Yoda Time which is a much nicer library to work with for Date/Time tasks, in my opinion.
http://joda-time.sourceforge.net/
任何一个都可以。我会坚持使用
Calendar
只是为了与 Java 版本保持一致。应该避免使用已弃用的方法,因为这是一个好习惯。如果有可行的替代方案,我会远离已弃用的东西,除非你有充分的理由这样做,例如速度。我怀疑从
Date
切换到Calendar
会导致速度显着下降。不过,您可能想对其进行基准测试,以防万一。Either one is fine. I would stick with
Calendar
just to be consistent with the Java version. Deprecated methods should be avoided if only because it's a good habit to get into.If there's a viable alternative, I would stay away from deprecated things unless you have a good reason to do so, such as speed. I doubt switching from
Date
toCalendar
would cause a significant loss in speed. You may want to benchmark it just in case though.如果 API 被弃用,它可能危险或有错误。如果存在建议的替代方案,您应该使用它们(并且不要习惯于忽略它们)。使用日历并不难获得您所需要的东西。如果您有特殊的日历操作要做,您可以尝试 Charles Goodwin 提到的 Joda - 但对于您的用例来说,似乎不需要依赖第三方库。
If an API is deprected it might be dangerous or buggy. If suggested alternatives exist you should use them (and don't get used to ignore them). Using Calendar is not that hard to get what you need. If you have special calendar operations to do you can try Joda as mentioned by Charles Goodwin - but for your use case there seems to be no need to depend on a third party library.
我不建议使用日期方法。我看不出有什么优势。作为程序员,在
Date
或Calendar
上调用该方法对您来说没有什么区别,不是吗?在Date
实例上调用它没有任何好处。正如您所指出的,这些方法已被弃用。这意味着它们可以随时从 API 中删除,恕不另行通知。事实上,它只能在 JVM 升级时发生。只有当您切换到恰好删除了它们的 JVM 时,您的代码才会停止工作。
因此,您的代码突然停止工作的风险很小,但也不是零。
I would not recommend using the Date methods. I see no advantage whatsoever. Calling that method on a
Date
orCalendar
makes no difference to you as a programmer, does it? There's no benefit at all to calling it on aDate
instance.As you've noted, these methods are deprecated. This means that they can be removed from the API without notice at any time. The reality is that it can only happen on a JVM upgrade. Your code will only stop working if you switch to a JVM that happens to have them removed.
So the risk is small that your code will suddenly stop working, but it's not zero.