DateEditor.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package com.fdkankan.common.util;
  2. import org.apache.commons.lang3.time.DateUtils;
  3. import java.beans.PropertyEditorSupport;
  4. import java.text.ParseException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. public class DateEditor extends PropertyEditorSupport {
  8. private boolean emptyAsNull;
  9. private String dateFormat = "yyyy-MM-dd HH:mm:ss";
  10. public static final String[] DATE_PATTERNS = {"yyyy", "yyyy-MM", "yyyyMM", "yyyy/MM", "yyyy-MM-dd", "yyyyMMdd",
  11. "yyyy/MM/dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss", "yyyy/MM/dd HH:mm:ss"};
  12. public DateEditor(boolean emptyAsNull) {
  13. this.emptyAsNull = emptyAsNull;
  14. }
  15. public DateEditor(boolean emptyAsNull, String dateFormat) {
  16. this.emptyAsNull = emptyAsNull;
  17. this.dateFormat = dateFormat;
  18. }
  19. public String getAsText() {
  20. Date date = (Date) getValue();
  21. return date != null ? new SimpleDateFormat(this.dateFormat).format(date) : "";
  22. }
  23. public void setAsText(String text) {
  24. if (text == null) {
  25. setValue(null);
  26. } else {
  27. String str = text.trim();
  28. if ((this.emptyAsNull) && ("".equals(str)))
  29. setValue(null);
  30. else
  31. try {
  32. setValue(DateUtils.parseDate(str, DATE_PATTERNS));
  33. } catch (ParseException e) {
  34. setValue(null);
  35. }
  36. }
  37. }
  38. }