Реализация времени суток на Java - PullRequest
3 голосов
/ 09 января 2010
package timeToys;

import java.util.regex.Pattern;


**
 * A DayTime is an immutable object that stores a moment of day represented in
 * hour, minutes and seconds. Day or year are not defined.
 * 
 * @author marius.costa <marius.costa@yahoo.com>
 */

public class DayTime {`enter code here`

    private int hour;// hour of the day
    private int minute;// minute of the hour
    private int second;// second of the minute
    private String time;// time as string

    private static final String TIME_LONG_FORMAT = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
    private static final String TIME_SHORT_FORMAT = "([01]?[0-9]|2[0-3]):[0-5][0-9]";

    /**
     * Class private constructor that creates new objects using inner builder.
     * 
     * @param timeBuilder - builder for new DayTime objects defined as inner class.
     */
    private DayTime(Builder timeBuilder) {
        this.hour = timeBuilder.hour;
        this.minute = timeBuilder.minute;
        this.second = timeBuilder.second;
        this.time = timeBuilder. time;
    }

    public int getHour() {
        return hour;
    }

    public int getMinute() {
        return minute;
    }

    public int getSecond() {
        return second;
    }

    @Override
    public String toString() {
        return time;
    }

    /**
     * Builder is a inner class that creates new DayTime objects based on int params
     * (hour, minute, second), or by parsing a String param formated as
     * 'HH:mm' or 'HH:mm:ss'.
     */
    public static class Builder {
        private int hour = 0;
        private int minute = 0;
        private int second = 0;
        private String time;

        /**
         * Constructor that creates a Builder from a String param formated as
         * 'HH:mm' or 'HH:mm:ss'.
         * @param time - must be formated as 'HH:mm' or 'HH:mm:ss'.
         */
        public Builder(String time) {
            this.time = time;
        }

        /**
         * Creates a DayTime object from the String {@link #time}.
         * The String {@code time} is innitialy parsed to validate time
         * in 24 hours format with regular expression.
         * If not, RuntimeExceptions will be thrown.
         *  
         * 
         * @return DayTime 
         * @throws IllegalArgumentException if the string isn't right formated.
         * @throws NumberFormatException if int values cannot be extracted from String time.  
         */
        public DayTime createTime() {
            String[] timeUnits = time.split(":");
            if(Pattern.compile(TIME_SHORT_FORMAT).matcher(time).matches()) {
                this.hour = Integer.parseInt(timeUnits[0]);
                this.minute = Integer.parseInt(timeUnits[1]);
            } else if(Pattern.compile(TIME_LONG_FORMAT).matcher(time).matches()) {
                this.hour = Integer.parseInt(timeUnits[0]);
                this.minute = Integer.parseInt(timeUnits[1]);
                this.second = Integer.parseInt(timeUnits[2]);
            } else {
                throw new IllegalArgumentException("Invalid time format" +
                " (Expected format: 'HH:mm' or 'HH:mm:ss').");
            }
            return new DayTime(this);
        }
    }
}

Ответы [ 4 ]

12 голосов
/ 09 января 2010

Использование JodaTime .

11 голосов
/ 09 января 2010

не делай этого. Не поддавайтесь искушению написать свой собственный код даты / времени. Это укусит тебя

используйте стандартный класс даты - даже если это кажется пустой тратой

1 голос
/ 09 января 2010

Вы можете добавить методы:

equals()

hash()

и реализовать сопоставимый интерфейс

int compareTo( Object other )

Кроме того, рекомендуется сделать его неизменным.

Например, если вы используете этот класс, чтобы проверить, должно ли что-то произойти:

 class Remainder {
     private String what;
     private DateTime when;


     public static Remainder remindMe( String what, DateTime when ) {
         Reminder r = new Reminder();
         r.what = what;
         r.when = when;
     }

     public boolean isTimeAlready() {
          //return DateTime.Builder.createTime().compareTo( this.when ) > 0;
          // implemented somehow 
          return isCurrentTimeGreaterThan( this.when ); // assume it return true if current time is after "when"
     }
  }

Если вы используете это так:

  DateTime atSix = new DateTime( 18, 0, 0 );

  Reminder reminder = Reminder.remindMe("Go for the milk", atSix );

И час меняется (по ошибке конечно)

  atSix.setHour( 1 );

Объекту "Напоминание" не будет иметь смысла, что переменная when является закрытой, поскольку ее ссылка хранится снаружи и не контролирует ее, поэтому она становится ненадежной.

Это может быть очень странная ошибка, которую вы можете представить. Использование неизменяемых объектов менее подвержено ошибкам. Вот почему основные объекты в Java, такие как String, Integer и многие другие, являются неизменяемыми.

Если вы можете прочитать эту книгу: Эффективная Java , она повернется на 180 градусов по сравнению с вашей перспективой Java.

0 голосов
/ 17 августа 2011

Check http://veyder -time.enblom.org - мощная и простая альтернатива java.util, joda-time и т. Д.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...