All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cdc.util.prefs.defaults.DatePreference Maven / Gradle / Ivy

There is a newer version: 0.9.0
Show newest version
package cdc.util.prefs.defaults;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.prefs.Preferences;

import cdc.util.prefs.AbstractPreference;

/**
 * Date preference (node, key) pair.
 *
 * @author Damien Carbonne
 */
public class DatePreference extends AbstractPreference {
    private final DateFormat format;

    /**
     * Enumeration of default formats.
     *
     * @author Damien Carbonne
     *
     */
    public enum Format {
        /**
         * Only the date part (year-month-day) is saved.
         */
        DATE("yyyy-MM-dd"),

        /**
         * Only the time part (hours:minutes:seconds) is saved.
         */
        TIME("HH:mm:ss"),

        /**
         * Date and time parts (year-month-day hours:minutes:seconds) are saved.
         */
        DATE_TIME("yyyy-MM-dd HH:mm:ss");

        private final String pattern;

        private Format(String pattern) {
            this.pattern = pattern;
        }

        public String getPattern() {
            return pattern;
        }
    }

    /**
     * Creates a date preference.
     *
     * @param node The Preferences node.
     * @param key The preferences key.
     * @param def The default value.
     * @param pattern The format pattern.
     */
    public DatePreference(Preferences node,
                          String key,
                          Date def,
                          String pattern) {
        super(Date.class,
              node,
              key,
              def);
        format = new SimpleDateFormat(pattern);
    }

    public DatePreference(Preferences node,
                          String key,
                          Date def,
                          Format format) {
        this(node, key, def, format.getPattern());
    }

    @Override
    protected String toString(Date value) {
        return format.format(value);
    }

    @Override
    protected Date fromString(String s) {
        try {
            return format.parse(s);
        } catch (final ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy