View Javadoc
1   package cn.home1.oss.lib.common;
2   
3   import org.joda.time.DateTime;
4   import org.joda.time.MutableDateTime;
5   import org.joda.time.format.DateTimeFormatter;
6   
7   import java.text.DateFormat;
8   import java.text.FieldPosition;
9   import java.text.ParsePosition;
10  import java.util.Date;
11  
12  /**
13   * Created by haolun on 17/1/10.
14   */
15  public class DateTimeFormatterWrapper extends DateFormat {
16  
17    private final DateTimeFormatter dateTimeFormatter;
18  
19    public DateTimeFormatterWrapper(final DateTimeFormatter dateTimeFormatter) {
20      this.dateTimeFormatter = dateTimeFormatter;
21    }
22  
23    @Override
24    public StringBuffer format(final Date date, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
25      this.dateTimeFormatter.printTo(toAppendTo, new DateTime(date, Defaults.UTC_P8));
26      return toAppendTo;
27    }
28  
29    @Override
30    public Date parse(final String source, final ParsePosition pos) {
31      final MutableDateTime mutableDateTime = new MutableDateTime();
32      this.dateTimeFormatter.parseInto(mutableDateTime, source, pos.getIndex());
33      return mutableDateTime.toDate();
34    }
35  }