简体   繁体   English

Java:如何使用日期/日历

[英]Java: how to use Date / Calendar

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. 现在如何使用Date/Calendar来避免必须使用自己的方法。 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. 不过,我需要两个,一个是setDates() ,用于设置注册的开始日期和结束日期,第二个是isOpen() ,如果学生尝试过早或过早注册,它将返回错误。 (Assuming the moment of applying is the moment the program is run, so basically "now") (假设应用的时刻是程序运行的时刻,因此基本上是“现在”)

The JDK's Date and Calendar classes are notoriously lacking in both functionality and ease of use. 众所周知,JDK的Date和Calendar类缺乏功能和易用性。

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. 我建议使用http://joda-time.sourceforge.net/中的Joda Date库使事情变得容易,但是据我所知,尚不存在可以完全满足您需求的库-我认为您是仍然需要自己写点东西。

It sounds like you care about dates, but not times, so beware of the JDK Date class, which incorporates date and time. 听起来您好像在乎日期,而不是时间,所以请当心JDK Date类,其中包含日期和时间。 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. Joda可以提供帮助-例如,它具有一个LocalDate类,它表示“天”-一个没有时间的日期。

isOpen() can be this simple: isOpen()可以很简单:

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) setDates()可以只是一个简单的设置方法(尽管您应该保护结束日期不能早于开始日期的不变式)

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 (eg through the Interval class and its containsNow() method ). 但是,这种类型的逻辑非常普遍,第三方的Joda-Time库为您进行了很好的封装(例如,通过Interval及其containsNow()方法 )。

I'd personally extend the class and then make my own setStartDate(date startDate) setEndDate(date endDate) isOpen() 我将亲自扩展该类,然后创建自己的setStartDate(date startDate)setEndDate(date endDate)isOpen()

Use @mark peters' isopen and just make the set assign the variables... 使用@mark peters'isopen并让该集合分配变量...

setDates - 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;
}

I assume you will use some kind of date picker that returns the date as a String. 我假设您将使用某种日期选择器,将日期作为字符串返回。

setDates will require this: setDates将需要以下内容:

  • Two String parameters; 两个字符串参数; start date and end date. 开始日期和结束日期。
  • Parsing of the parameters (SimpleDateFormat). 解析参数(SimpleDateFormat)。
  • Knowledge of the date format that is returned by the picker (I'll assume DD MON YYYY, for example: "12 Oct 2011") 了解选择器返回的日期格式(我假设是DD MON YYYY,例如:“ 12 Oct 2011”)
  • Two Date objects to store the date: start date and end date. 两个用于存储日期的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. 将结束日期调整为11:59p。

isOpen is easier. isOpen更容易。

  • Verify that startDate and endDate are not null. 验证startDate和endDate不为null。
  • Get the current date (new Date()). 获取当前日期(新的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.
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM