Package com.j256.ormlite.field.types

Source Code of com.j256.ormlite.field.types.BaseDateType

package com.j256.ormlite.field.types;

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

import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.field.SqlType;

/**
* Base class for all of the {@link java.sql.Date} class types.
*
* @author graywatson
*/
public abstract class BaseDateType extends BaseDataType {

  public static final DateStringFormatConfig defaultDateFormatConfig = new DateStringFormatConfig(
      "yyyy-MM-dd HH:mm:ss.SSSSSS");

  protected BaseDateType(SqlType sqlType, Class<?>[] classes) {
    super(sqlType, classes);
  }

  protected static DateStringFormatConfig convertDateStringConfig(FieldType fieldType) {
    if (fieldType == null) {
      return defaultDateFormatConfig;
    }
    DateStringFormatConfig configObj = (DateStringFormatConfig) fieldType.getDataTypeConfigObj();
    if (configObj == null) {
      return defaultDateFormatConfig;
    } else {
      return (DateStringFormatConfig) configObj;
    }
  }

  protected static Date parseDateString(DateStringFormatConfig formatConfig, String dateStr) throws ParseException {
    DateFormat dateFormat = formatConfig.getDateFormat();
    return dateFormat.parse(dateStr);
  }

  protected static String normalizeDateString(DateStringFormatConfig formatConfig, String dateStr)
      throws ParseException {
    DateFormat dateFormat = formatConfig.getDateFormat();
    Date date = dateFormat.parse(dateStr);
    return dateFormat.format(date);
  }

  protected static String formatDate(DateStringFormatConfig formatConfig, Date date) {
    DateFormat dateFormat = formatConfig.getDateFormat();
    return dateFormat.format(date);
  }

  protected static class DateStringFormatConfig {
    private final ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
    final String dateFormatStr;
    public DateStringFormatConfig(String dateFormatStr) {
      this.dateFormatStr = dateFormatStr;
    }
    public DateFormat getDateFormat() {
      DateFormat dateFormat = threadLocal.get();
      if (dateFormat == null) {
        dateFormat = new SimpleDateFormat(dateFormatStr);
        threadLocal.set(dateFormat);
      }
      return dateFormat;
    }
    @Override
    public String toString() {
      return dateFormatStr;
    }
  }
}
TOP

Related Classes of com.j256.ormlite.field.types.BaseDateType

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.