Skip to content

Instantly share code, notes, and snippets.

@aVolpe
Last active May 9, 2019 11:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aVolpe/6558296 to your computer and use it in GitHub Desktop.
Save aVolpe/6558296 to your computer and use it in GitHub Desktop.
DateFormat
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
import javax.el.Expression;
import javax.faces.component.FacesComponent;
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.stereotype.Component;
/**
* Singleton que se encarga de realizar los formatos de {@link Date} y
* {@link BigDecimal} en el sistema.
* <p>
* Todas las conversiones de {@link String} a {@link Date} o {@link BigDecimal}
* <b>deben</b> ser realizadas por esta clase.
* </p>
* <p>
* Para acceder a este componente se pueden utilizar alguno de los siguientes
* mecanismos:
* <ol>
* <li> {@link Expression}: #{fp}</li>
* <li> {@link Component}: {@literal @}{@link Autowire} {@link FormatProvider}
* fp;</li>
* <li> {@link FacesComponent}: Util.getSpringBeanByJSFContext(context,
* FormatProvider.class)</li>
*
* </ol>
* </p>
*
* @author Arturo Volpe
* @since 2.2
* @version 1.0 Sep 10, 2013
*/
@Component(value = DateFormat.FORMAT_PROVIDER_NAME)
public class DateFormat {
/**
* Nombre de este bean, se reduce el nombre para disminuir la verbosidad
* desde jsf.
*/
public static final String FORMAT_PROVIDER_NAME = "df";
/**
* Formato de las fechas en el sistema. Este formato incluye el año
* completo, y esta separado por guiones.
* <p>
* Si se desea que se formateen hora y minutos ver {@link #DATETIME_FORMAT}
* </p>
*
* @see #DATE_SHORT_FORMAT
*/
public static final String DATE_FORMAT = "dd-MM-yyyy";
/**
* Formato de las fechas cortas, este formato incluye los dos últimos
* numeros de la fecha.
* <p>
* Si se desea que se formateen hora y los minutos, ver
* {@link #DATETIME_SHORT_FORMAT}
* </p>
*
* @see #DATE_FORMAT
*/
public static final String DATE_SHORT_FORMAT = "dd-MM-yy";
/**
* Formato de las fechas que representan horas y minutos, no incluye los
* segundos.
*
*/
public static final String TIME_FORMAT = "HH:mm";
/**
* Formato de las fechas con horas y minutos.
* <p>
* Este formato incluye el año completo separado por guiones.
* </p>
*
*
* @see #DATE_SHORT_FORMAT
*/
public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm";
/**
* Formato de las fechas cortas con horas y minutos.
* <p>
* Este formato incluye el año completo separado por guiones.
* </p>
*/
public static final String DATETIME_SHORT_FORMAT = "dd-MM-yy HH:mm";
private static final String EMPTY_STRING = "";
private Map<String, SimpleDateFormat> formats;
private boolean initialized = false;
private DecimalFormatSymbols dfs;
private synchronized void init() {
if (initialized) {
return;
}
initialized = true;
formats = new HashMap<String, SimpleDateFormat>(5);
formats.put(DATE_FORMAT, new SimpleDateFormat(DATE_FORMAT));
formats.put(DATE_SHORT_FORMAT, new SimpleDateFormat(DATE_SHORT_FORMAT));
formats.put(TIME_FORMAT, new SimpleDateFormat(TIME_FORMAT));
formats.put(DATETIME_FORMAT, new SimpleDateFormat(DATETIME_FORMAT));
formats.put(DATETIME_SHORT_FORMAT, new SimpleDateFormat(
DATETIME_SHORT_FORMAT));
for (SimpleDateFormat sdf : formats.values()) {
sdf.setLenient(false);
}
}
/**
* Formatea una fecha con el formato {@link #DATE_SHORT_FORMAT}
* <p>
* Esta fecha debe ser usada en grillas y en lugares donde el espacio es
* reducido. Si es el caso en que se deben mostrar horas y minutos, se debe
* usar {@link #asShortDateTime(Date)} o {@link #asTime(Date)}.
* </p>
*
* @param date
* fecha que se desea parsear.
* @return cadena con el formato {@link #DATE_SHORT_FORMAT}, retorna
* <code>""</code> si el parámetro es <code>null</code>
*/
public String asShortDate(@Nullable Date date) {
return dateToString(date, DATE_SHORT_FORMAT);
}
public Date parseShortDate(@Nullable String string) throws ParseException {
return stringToDate(string, DATE_SHORT_FORMAT);
}
public String asDate(@Nullable Date date) {
return dateToString(date, DATE_FORMAT);
}
public Date parseDate(@Nullable String string) throws ParseException {
return stringToDate(string, DATE_FORMAT);
}
public String asTime(@Nullable Date date) {
return dateToString(date, TIME_FORMAT);
}
public Date parseTime(@Nullable String string) throws ParseException {
return stringToDate(string, TIME_FORMAT);
}
public String asDateTime(@Nullable Date date) {
return dateToString(date, DATETIME_FORMAT);
}
public Date parseDateTime(@Nullable String string) throws ParseException {
return stringToDate(string, DATETIME_FORMAT);
}
public String asShortDateTime(@Nullable Date date) {
return dateToString(date, DATETIME_SHORT_FORMAT);
}
public Date parseShortDateTime(@Nullable String string)
throws ParseException {
return stringToDate(string, DATETIME_SHORT_FORMAT);
}
protected synchronized String dateToString(Date date, String format) {
if (date == null) {
return EMPTY_STRING;
}
return getFormat(format).format(date);
}
/**
* @param string
* @return
* @throws ParseException
*/
protected synchronized Date stringToDate(String string, String format)
throws ParseException {
if (string == null || EMPTY_STRING.equals(string)) {
return null;
}
SimpleDateFormat sdf = getFormat(format);
ParsePosition psp = new ParsePosition(0);
if (string.length() != format.length()) {
throw new ParseException("Imposible parsear", 0);
}
Date toRet = sdf.parse(string, psp);
if (psp.getIndex() != string.length()) {
throw new ParseException("Imposible parsear", psp.getIndex());
}
return toRet;
}
/**
* Provee un formato
*
* @param format
* @return
*/
private SimpleDateFormat getFormat(String format) {
if (!initialized) {
init();
}
if (!formats.containsKey(format)) {
throw new IllegalArgumentException("Unknow format " + format);
}
return formats.get(format);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment