Java:如何使用日期/日历
我正在为我的大学制作一个小项目,该项目应该招收学生参加不同的课程。不过,我确实有一个问题,每门课程都有开始/结束注册日。我现在如何使用 Date/Calendar
来避免必须创建自己的方法。不过,我需要两个,一个是 setDates()
,用于设置注册的开始和结束日期,第二个是 isOpen()
,如果学生尝试过早或过晚注册。 (假设申请的时刻就是程序运行的时刻,所以基本上是“现在”)
I'm making a small project for my university which is supposed to enroll students into different courses. I do have one issue though, each course has start/end enrollment day. How can I now use Date/Calendar
to avoid having to make my own method. I will need two though, one is setDates()
, used to set start and end dates for enrollment, and second is isOpen()
, which will return error if a student tries to enroll too early or too late. (Assuming the moment of applying is the moment the program is run, so basically "now")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
众所周知,JDK 的 Date 和 Calendar 类缺乏功能性和易用性。
我建议使用 http://joda-time.sourceforge.net/ 中的 Joda Date 库为了让事情变得更容易,但据我所知,没有现有的库能够完全满足您的需求 - 我认为您仍然需要自己编写一些东西。
听起来您关心的是日期,而不是时间,因此请注意 JDK Date 类,它包含日期和时间。如果您不知道这一点,则在比较日期时可能会导致各种意外行为。 Joda 可以提供帮助 - 例如,它有一个 LocalDate 类,它代表“天” - 没有时间的日期。
The JDK's Date and Calendar classes are notoriously lacking in both functionality and ease of use.
I'd suggest using the Joda Date library from http://joda-time.sourceforge.net/ to make things easier, but as far as I know, there is no existing library that exactly meets your needs - I think that you are still going to have to write something yourself.
It sounds like you care about dates, but not times, so beware of the JDK Date class, which incorporates date and time. This can cause all sorts of unexpected behavior when comparing Dates if you are not aware of this. Joda can help - it has, for instance, a LocalDate class which represents a 'day' - a date without a time.
isOpen()
可以如此简单:setDates()
可以只是一个简单的 setter(尽管您应该保护结束日期不能早于开始日期的不变量)这种类型逻辑很常见,第三方 Joda-Time 库很好地为您封装了它(例如通过
Interval
类 及其containsNow()
方法)。isOpen()
can be this simple:setDates()
can just be a simple setter (though you should protect the invariant that end date cannot be before start date)This type of logic is very common though and the third-party Joda-Time library does a very good job of encapsulating it for you (e.g. through the
Interval
class and itscontainsNow()
method).我会亲自扩展课程,然后制作自己的课程
setStartDate(日期开始日期)
setEndDate(日期结束日期)
isOpen()
使用@mark peters' isopen 并让集合分配变量...
I'd personally extend the class and then make my own
setStartDate(date startDate)
setEndDate(date endDate)
isOpen()
Use @mark peters' isopen and just make the set assign the variables...
setDates -
isOpen -
setDates -
isOpen -
我假设您将使用某种以字符串形式返回日期的日期选择器。
setDates 将需要这个:
isOpen 更容易。
这是一些代码:
I assume you will use some kind of date picker that returns the date as a String.
setDates will require this:
isOpen is easier.
Here is some code: