开发者

Java: how to use Date / Calendar

开发者 https://www.devze.com 2023-04-13 08:12 出处:网络
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 ca

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")


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() 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).


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 -

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:

  • 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.
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号