Java:如何使用日期/日历

发布于 2024-12-10 14:47:23 字数 238 浏览 0 评论 0原文

我正在为我的大学制作一个小项目,该项目应该招收学生参加不同的课程。不过,我确实有一个问题,每门课程都有开始/结束注册日。我现在如何使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

情绪操控生活 2024-12-17 14:47:23

众所周知,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.

感受沵的脚步 2024-12-17 14:47:23

isOpen() 可以如此简单:

public boolean isOpen() {
    Date now = new Date();
    return !now.before(startDate) && !now.after(endDate);
}

setDates() 可以只是一个简单的 setter(尽管您应该保护结束日期不能早于开始日期的不变量)

private Date startDate, endDate;

public void setDates(Date startDate, Date endDate) {
    Date startCopy = new Date(startDate);
    Date endCopy = new Date(endDate);
    if ( startCopy.after(endCopy) ) {
        throw new IllegalArgumentException("start must not be after end");
    }

    this.startDate = startCopy;
    this.endDate = endCopy;
 }

这种类型逻辑很常见,第三方 Joda-Time 库很好地为您封装了它(例如通过 Interval 及其containsNow() 方法)。

isOpen() can be this simple:

public boolean isOpen() {
    Date now = new Date();
    return !now.before(startDate) && !now.after(endDate);
}

setDates() can just be a simple setter (though you should protect the invariant that end date cannot be before start date)

private Date startDate, endDate;

public void setDates(Date startDate, Date endDate) {
    Date startCopy = new Date(startDate);
    Date endCopy = new Date(endDate);
    if ( startCopy.after(endCopy) ) {
        throw new IllegalArgumentException("start must not be after end");
    }

    this.startDate = startCopy;
    this.endDate = endCopy;
 }

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 its containsNow() method).

青萝楚歌 2024-12-17 14:47:23

我会亲自扩展课程,然后制作自己的课程
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...

戈亓 2024-12-17 14:47:23

setDates -

public void setDates(Date start, Date end) {
    this.start = start;
    this.end = end;
}

isOpen -

public boolean isOpen() {
    Date now = new Date();
    if(now.before(this.start) || now.after(this.end)) {
        return false;
    }
    return true;
}

setDates -

public void setDates(Date start, Date end) {
    this.start = start;
    this.end = end;
}

isOpen -

public boolean isOpen() {
    Date now = new Date();
    if(now.before(this.start) || now.after(this.end)) {
        return false;
    }
    return true;
}
做个少女永远怀春 2024-12-17 14:47:23

我假设您将使用某种以字符串形式返回日期的日期选择器。

setDates 将需要这个:

  • 两个字符串参数;开始日期和结束日期。
  • 解析参数(SimpleDateFormat)。
  • 了解选择器返回的日期格式(我假设 DD MON YYYY,例如:“12 Oct 2011”)
  • 两个用于存储日期的 Date 对象:开始日期和结束日期。
  • 使用日历清除日期中不需要的部分(小时、分钟、秒和毫秒)。
  • 将结束日期调整为晚上 11:59。

isOpen 更容易。

  • 验证 startDate 和 endDate 不为空。
  • 获取当前日期(new Date())。
  • 检查是否超出范围。

这是一些代码:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

/**
 * @author David W. Burhans
 * 
 */
public final class Registration
{
    private static final DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
    private static Date endDate;
    private static Date startDate;

    private static boolean isOpen()
    {
        Date now = new Date();
        boolean returnValue;

        if (now.before(startDate) || now.after(endDate))
        {
            returnValue = false;
        }
        else
        {
            returnValue = true;
        }

        return returnValue;
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        setDates("21 Jan 2012", "28 Jan 2012");

        System.out.print("Start Date: ");
        System.out.println(startDate);
        System.out.print("End Date: ");
        System.out.println(endDate);

        System.out.print("Is today in range: ");
        System.out.println(isOpen());
    }

    private static void setDates(final String startDateString, final String endDateString)
    {
        // All or nothing.
        if (StringUtils.isNotBlank(startDateString) && StringUtils.isNotBlank(endDateString))
        {
            Calendar calendar = Calendar.getInstance();
            Date workingDate;

            try
            {
                workingDate = dateFormat.parse(endDateString);

                calendar.setTime(workingDate);
                calendar.set(Calendar.HOUR, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);

                endDate = calendar.getTime();
            }
            catch (ParseException exception)
            {
                //System.out.println("endDate parse Exception");
                // log that endDate is invalid. throw exception.
            }

            try
            {
                workingDate = dateFormat.parse(startDateString);

                calendar.setTime(workingDate);
                calendar.set(Calendar.HOUR, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);

                startDate = calendar.getTime();
            }
            catch (ParseException exception)
            {
                //System.out.println("startDate parse Exception");
                // log that startDate is invalid. throw exception.
            }
        }
        else
        {
            // throw exception indicating which is bad.
        }
    }
}

I assume you will use some kind of date picker that returns the date as a String.

setDates will require this:

  • Two String parameters; start date and end date.
  • Parsing of the parameters (SimpleDateFormat).
  • Knowledge of the date format that is returned by the picker (I'll assume DD MON YYYY, for example: "12 Oct 2011")
  • Two Date objects to store the date: start date and end date.
  • Use of a Calendar to clear the unwanted parts of the Date (hour, minute, second, and milliseconds).
  • Adjust the end date to 11:59p.

isOpen is easier.

  • Verify that startDate and endDate are not null.
  • Get the current date (new Date()).
  • Check if it is outside the range.

Here is some code:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

/**
 * @author David W. Burhans
 * 
 */
public final class Registration
{
    private static final DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
    private static Date endDate;
    private static Date startDate;

    private static boolean isOpen()
    {
        Date now = new Date();
        boolean returnValue;

        if (now.before(startDate) || now.after(endDate))
        {
            returnValue = false;
        }
        else
        {
            returnValue = true;
        }

        return returnValue;
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        setDates("21 Jan 2012", "28 Jan 2012");

        System.out.print("Start Date: ");
        System.out.println(startDate);
        System.out.print("End Date: ");
        System.out.println(endDate);

        System.out.print("Is today in range: ");
        System.out.println(isOpen());
    }

    private static void setDates(final String startDateString, final String endDateString)
    {
        // All or nothing.
        if (StringUtils.isNotBlank(startDateString) && StringUtils.isNotBlank(endDateString))
        {
            Calendar calendar = Calendar.getInstance();
            Date workingDate;

            try
            {
                workingDate = dateFormat.parse(endDateString);

                calendar.setTime(workingDate);
                calendar.set(Calendar.HOUR, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);

                endDate = calendar.getTime();
            }
            catch (ParseException exception)
            {
                //System.out.println("endDate parse Exception");
                // log that endDate is invalid. throw exception.
            }

            try
            {
                workingDate = dateFormat.parse(startDateString);

                calendar.setTime(workingDate);
                calendar.set(Calendar.HOUR, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);

                startDate = calendar.getTime();
            }
            catch (ParseException exception)
            {
                //System.out.println("startDate parse Exception");
                // log that startDate is invalid. throw exception.
            }
        }
        else
        {
            // throw exception indicating which is bad.
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文