com.wedian.site.common.web.DateEditor.java Source code

Java tutorial

Introduction

Here is the source code for com.wedian.site.common.web.DateEditor.java

Source

/*
 * Copyright 2005-2013 shopxx.net. All rights reserved.
 * Support: http://www.shopxx.net
 * License: http://www.shopxx.net/license
 */
package com.wedian.site.common.web;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.wedian.site.common.utils.CommonAttributes;
import org.apache.commons.lang3.time.DateUtils;

/**
 * ?
 * 
 * @author wanliang
 * @version 3.0
 */
public class DateEditor extends PropertyEditorSupport {

    /** ? */
    private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /** ??null */
    private boolean emptyAsNull;

    /** ? */
    private String dateFormat = DEFAULT_DATE_FORMAT;

    /**
     * @param emptyAsNull
     *            ??null
     */
    public DateEditor(boolean emptyAsNull) {
        this.emptyAsNull = emptyAsNull;
    }

    /**
     * @param emptyAsNull
     *            ??null
     * @param dateFormat
     *            ?
     */
    public DateEditor(boolean emptyAsNull, String dateFormat) {
        this.emptyAsNull = emptyAsNull;
        this.dateFormat = dateFormat;
    }

    /**
     * ?
     * 
     * @return 
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return value != null ? new SimpleDateFormat(dateFormat).format(value) : "";
    }

    /**
     * 
     * 
     * @param text
     *            
     */
    @Override
    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            String value = text.trim();
            if (emptyAsNull && "".equals(value)) {
                setValue(null);
            } else {
                try {
                    setValue(DateUtils.parseDate(value, CommonAttributes.DATE_PATTERNS));
                } catch (ParseException e) {
                    setValue(null);
                }
            }
        }
    }

}