de.decidr.ui.view.DateField.java Source code

Java tutorial

Introduction

Here is the source code for de.decidr.ui.view.DateField.java

Source

/*
 * The DecidR Development Team licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package de.decidr.ui.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import de.decidr.ui.view.uibuilder.FormattedValueField;

/**
 * Like Vaadin's DateField, except it uses ISO 8601 formatted
 * date strings as input and output.
 *
 * @author Wolfgang Fellger
 */
public class DateField extends com.vaadin.ui.DateField implements FormattedValueField {

    private static final long serialVersionUID = 4167224694273997466L;

    protected static final String[] DATEFORMATS = new String[] { "yyyy-MM-dd'T'HH:mm'Z'", "yyyy-MM-dd" };
    protected final SimpleDateFormat[] dfs;

    public DateField(String label) {
        super(label);
        dfs = new SimpleDateFormat[DATEFORMATS.length];
        for (int i = 0; i < DATEFORMATS.length; i++) {
            dfs[i] = new SimpleDateFormat(DATEFORMATS[i]);
            dfs[i].setTimeZone(TimeZone.getTimeZone("UTC"));
        }
    }

    /**
     * Parses dateString according to ISO 8601 and set it as
     * value of the field. Invalid values will set the current
     * time and date as value.
     *
     * @param dateString
     *        String in any of the formats defined in {@link DATEFORMATS}
     *        (currently yyyy-MM-ddThh:mmZ or yyyy-MM-dd).
     */
    public void setValue(String dateString) {
        Date date = new Date();
        if (!dateString.isEmpty()) {
            for (SimpleDateFormat df : dfs) {
                try {
                    date = df.parse(dateString);
                    break;
                } catch (ParseException e) {
                    continue;
                }
            }
        }
        this.setValue(date);
    }

    public String getDecidrValue() {
        return dfs[0].format((Date) super.getValue());
    }
}