English 中文(简体)
代表 Java物体营业时间的最佳途径是什么?
原标题:Which is the best way to represent the business opening hours in a Java object?
  • 时间:2011-11-02 12:33:19
  •  标签:
  • java

I need to represent opening hours, and a method which returns true/false for a certain day and time. Is there any package which has this functionality already?

Edit: Basically I would need to construct an object with data out of db or a file, then perform a basic check against the object, like if it s closed at a certain moment.

The problem was that some businesses will have working hours after 00:00 so it overlaps the next day. In this case I figure out that the object should be able to support multiple time frames per day, also to cover lunch brakes.

问题回答

您可以通过使用<条码>Calendar创建班级,看看其工作日和工作时间。

class BusinessHour{

public void isOpenNow(){
  Calendar calNow = Calendar.getInstance();
    //check the rules for example , if day is MOn-FRi and time is 9-18.
  }
}

I don t think there would be a ready made because each business has its own specification, You could probably make if configurable so that it fixes for all the business, provide the conf parameter externally to the class for better design

我在反对下在哈希斯提储存开幕式。 用午夜的二秒而不是“800”或“1600”的二秒,便可方便地简化例灯。

public class OpeningHours {
  public enum DAY {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
  }

public OpeningHours(DAY day, Integer from, Integer to) {
    this.day = day;
    this.from = from; // format time using 800 for 8:00am or 2300 for 23:00
    this.to = to;
}

@Override
public String toString() {
    return "OpeningHours [day=" + day + ", from=" + from + ", to=" + to + ", isAllDay=" + isAllDay + "]";
}

public OpeningHours() {

}

public DAY day;
public Integer from;
public Integer to;
public boolean isAllDay = false;

public void isOpenx(DateTime start) {

}

public boolean isOpen(DateTime start) {

    if (day.ordinal() != start.getDayOfWeek() - 1) {
        return false;
    }

    if (isAllDay)
        return true;

    String f = String.format("%04d", from);
    String t = String.format("%04d", to);

    Integer fh = Integer.valueOf(f.substring(0, 2));
    Integer fm = Integer.valueOf(f.substring(2));

    Integer th = Integer.valueOf(t.substring(0, 2));
    Integer tm = Integer.valueOf(t.substring(2));

    DateTime intStart = start.withHourOfDay(fh).withMinuteOfHour(fm);
    DateTime intEnd = start.withHourOfDay(th).withMinuteOfHour(tm);

    if (intStart.equals(start) || intEnd.equals(start)) {
        return true;
    }
    if (intStart.isBefore(start) && intEnd.isAfter(start)) {
        return true;
    }

    return false;

}
}
HashSet<OpeningHours> hours = new HashSet<OpeningHours>();
hours.add(new OpeningHours(OpeningHours.DAY.MONDAY, 800, 1200));
hours.add(new OpeningHours(OpeningHours.DAY.MONDAY, 1230, 1600));


DateTime dateToCheck = new DateTime(2012, 9, 4, 8, 00, 0, 0);

for (OpeningHours item : hours) {
  boolean isOpen = item.isOpen(dateToCheck );
  if (isOpen){
    System.out.println("Is Open!");
  }
}

In Java 8, you can represent it as a set of openingTimes objects:

该套:

 Set<OpeningTimes> openingTimes = new HashSet<>();

OpeningTimes

import java.time.DayOfWeek;
import java.time.LocalTime;

public class OpeningTimes {
    private DayOfWeek dayOfWeek;
    private LocalTime from;
    private LocalTime to;

    public DayOfWeek getDayOfWeek() {
        return dayOfWeek;
    }

    public void setDayOfWeek(DayOfWeek dayOfWeek) {
        this.dayOfWeek = dayOfWeek;
    }

    public LocalTime getFrom() {
        return from;
    }

    public void setFrom(LocalTime from) {
        this.from = from;
    }

    public LocalTime getTo() {
        return to;
    }

    public void setTo(LocalTime to) {
        this.to = to;
    }
}

也许没有一揽子方案能够执行你的具体业务逻辑。

例如,你是否需要在一年的某一天凌驾于标准开放日之上,例如关闭特别活动? 关于公共假日,你是否为这些假期开放?

我提出的简单解决办法是:

  1. Create a database table with (day, opening time, closing time) as fields
  2. Create a function that take a day and time as parameters, and looks up in the database table to see if is within the opening/closing times for given day
  3. Provide an easy way for business users to update the open/closing times after pre-populating them with your standard times

以下类别还考虑到在规定日期整天未开一件事(如一栋大楼)的情况。

import org.jetbrains.annotations.NotNull;

import java.time.LocalTime;
import java.util.Objects;

/**
 * {@code OpeningHours} represents the opening hours of a single day of a "thing"
 * (e.g. a building). The opening- and closing hour are independent of timezones.
 */
public class OpeningHours {
    private boolean opensToday;
    private LocalTime openingHour;
    private LocalTime closingHour;

    /**
     * A reusable {@code OpeningHours} that is always closed.
     */
    private static OpeningHours closedInstance = new OpeningHours();

    /**
     * Constructs a new {@code OpeningHours} for a thing that does not open at this specific day.
     */
    public OpeningHours() {
        opensToday = false;
    }

    /**
     * Constructs a new {@code OpeningHours} for a thing that does open today.
     *
     * @param openingHour the opening hour of the thing, inclusive. Must be strictly less than the closingHour
     * @param closingHour the closing hour of the thing, exclusive. Must be strictly more than the openingHour
     */
    public OpeningHours(@NotNull LocalTime openingHour, @NotNull LocalTime closingHour) {
        Objects.requireNonNull(openingHour);
        Objects.requireNonNull(closingHour);

        if (openingHour.compareTo(closingHour) >= 0)
            throw new IllegalArgumentException("the openingHour must be strictly less than the closingHour");

        this.opensToday = true;
        this.openingHour = openingHour;
        this.closingHour = closingHour;
    }

    /**
     * Returns whether the thing this {@code OpeningHours} belongs to will open today.
     *
     * @return the value of {@link #opensToday}
     */
    public boolean opensToday() {
        return opensToday;
    }

    /**
     * Returns whether the provided {@code time} is within the opening hours. More specifically this method returns
     * {@code true} when {@code time} is equal to or greater than {@code this#getOpeningHour()} and strictly less
     * than {@code this.getClosingHour()}.
     *
     * @param time the time at wh
     * @return {@code true} if {@code time} is greater than or equal to {@link #openingHour} and strictly less than
     *         {@link #closingHour}.
     */
    public boolean isOpen(LocalTime time) {
        if (!opensToday)
            return false;
        return (openingHour.compareTo(time) <= 0) && (closingHour.compareTo(time) > 0) ;
    }

    /**
     * Returns whether the current time is within the opening hours.
     * 
     * @see #isOpen(LocalTime)
     */
    public boolean isOpen() {
        return this.isOpen(LocalTime.now());
    }


    /**
     * @return an {@code OpeningHours} for a thing that is permanently closed on this day.
     */
    public OpeningHours getClosedInstance() {
        return closedInstance;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        OpeningHours that = (OpeningHours) o;

        if (opensToday != that.opensToday) return false;
        if (!Objects.equals(openingHour, that.openingHour)) return false;
        return Objects.equals(closingHour, that.closingHour);
    }

    @Override
    public int hashCode() {
        int result = (opensToday ? 1 : 0);
        result = 31 * result + (openingHour != null ? openingHour.hashCode() : 0);
        result = 31 * result + (closingHour != null ? closingHour.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "OpeningHours{" +
                "opensToday=" + opensToday +
                ", openingHour=" + openingHour +
                ", closingHour=" + closingHour +
                 } ;
    }
}





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签