Package net.sourceforge.javautil.common.coersion.impl

Source Code of net.sourceforge.javautil.common.coersion.impl.CoersionUtilDate

package net.sourceforge.javautil.common.coersion.impl;

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

import net.sourceforge.javautil.common.coersion.CoersionException;
import net.sourceforge.javautil.common.exception.ThrowableManagerRegistry;

/**
* Standard conversion for {@link Date}'s.
*
* @author elponderador
* @author $Author: ponderator $
* @version $Id: CoersionUtilDate.java 1792 2010-02-03 01:00:49Z ponderator $
*/
public class CoersionUtilDate extends CoersionAbstract<CharSequence, Date> {
 
  public static final String[] DATE_FORMATS = {
    "MM/dd/yyyy hh:mm:ssa ZZZ", "MM/dd/yyyy hh:mm:ssa", "MM/dd/yyyy hh:mm", "MM/dd/yyyy"
  };
 
  public SimpleDateFormat[] format;

  public CoersionUtilDate() {
    super(CharSequence.class, Date.class);
   
    this.format = new SimpleDateFormat[DATE_FORMATS.length];
    for (int f=0; f<this.format.length; f++) this.format[f] = new SimpleDateFormat(DATE_FORMATS[f]);
  }

  public Object coerce(Object original, Class target) {
    if (original instanceof CharSequence) {
      for (SimpleDateFormat format : this.format) {
        try {
          return format.parse( String.valueOf( original ) );
        } catch (ParseException e) {}
      }
    } else if (original instanceof Date) {
      return format[0].format( (Date) original );
    }

    throw new CoersionException("Could not convert: " + original + " to " + target);
  }

}
TOP

Related Classes of net.sourceforge.javautil.common.coersion.impl.CoersionUtilDate

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.