001: /*
002: * @(#) DateConverter.java
003: *
004: * Copyright 2002 - 2003 JIDE Software. All rights reserved.
005: */
006: package com.jidesoft.converter;
007:
008: import java.text.DateFormat;
009: import java.text.ParseException;
010: import java.text.SimpleDateFormat;
011: import java.util.Calendar;
012: import java.util.Date;
013:
014: /**
015: * Converter which converts Date to String and converts it back.
016: */
017: public class MonthConverter implements ObjectConverter {
018:
019: /**
020: * Default ConverterContext for MonthConverter.
021: */
022: public static ConverterContext CONTEXT_MONTH = new ConverterContext(
023: "Calendar.Month");
024:
025: private DateFormat _conciseFormat = new SimpleDateFormat("MMyy");
026: private DateFormat _shortFormat = new SimpleDateFormat("MM/yy");
027: private DateFormat _mediumFormat = new SimpleDateFormat("MM, yyyy");
028: private DateFormat _longFormat = new SimpleDateFormat("MMMMM, yyyy");
029:
030: private DateFormat _defaultFormat = _shortFormat;
031:
032: /**
033: * Creates a new CalendarConverter.
034: */
035: public MonthConverter() {
036: }
037:
038: public String toString(Object object, ConverterContext context) {
039: if (object == null || !(object instanceof Calendar)) {
040: return "";
041: } else {
042: return _defaultFormat.format(((Calendar) object).getTime());
043: }
044: }
045:
046: public boolean supportToString(Object object,
047: ConverterContext context) {
048: return true;
049: }
050:
051: public Object fromString(String string, ConverterContext context) {
052: Calendar calendar = Calendar.getInstance();
053: try {
054: Date time = _defaultFormat.parse(string);
055: calendar.setTime(time);
056: } catch (ParseException e1) { // if current formatter doesn't work try those default ones.
057: try {
058: Date time = _shortFormat.parse(string);
059: calendar.setTime(time);
060: } catch (ParseException e2) {
061: try {
062: Date time = _mediumFormat.parse(string);
063: calendar.setTime(time);
064: } catch (ParseException e3) {
065: try {
066: Date time = _longFormat.parse(string);
067: calendar.setTime(time);
068: } catch (ParseException e4) {
069: try {
070: Date time = _conciseFormat.parse(string);
071: calendar.setTime(time);
072: } catch (ParseException e5) {
073: return null; // nothing works just return null so that old value will be kept.
074: }
075: }
076: }
077: }
078: }
079: return calendar;
080: }
081:
082: public boolean supportFromString(String string,
083: ConverterContext context) {
084: return true;
085: }
086:
087: /**
088: * Gets DefaultFormat to format an calendar.
089: *
090: * @return DefaultFormat
091: */
092: public DateFormat getDefaultFormat() {
093: return _defaultFormat;
094: }
095:
096: /**
097: * Sets DefaultFormat to format an calendar.
098: *
099: * @param defaultFormat the default format to format a calendar.
100: */
101: public void setDefaultFormat(DateFormat defaultFormat) {
102: _defaultFormat = defaultFormat;
103: }
104: }
|