br.com.jarch.faces.converter.YearMonthJsfConverter Maven / Gradle / Ivy
package br.com.jarch.faces.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import java.io.Serializable;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import static java.time.format.DateTimeFormatter.ofPattern;
@FacesConverter("br.com.jarch.faces.converter.yearMonthConverter")
public class YearMonthJsfConverter implements Serializable, Converter {
@Override
public YearMonth getAsObject(FacesContext context, UIComponent component, String value) {
try {
String newValue = value;
if (newValue == null || newValue.isEmpty() || newValue.replaceAll("_", "").replace("/", "").isEmpty()) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yyyy");
if (newValue.length() == 10) {
newValue = newValue.substring(3);
}
return YearMonth.parse(newValue, formatter);
} catch (Exception ex) {
return null;
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return null;
}
if (value.toString().isEmpty()) {
return "";
}
YearMonth yearMonth = (YearMonth) value;
return yearMonth.format(ofPattern("MM/yyyy"));
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy