br.com.jarch.faces.converter.LocalDateTimeJsfConverter Maven / Gradle / Ivy
package br.com.jarch.faces.converter;
import org.primefaces.component.calendar.Calendar;
import org.primefaces.component.datepicker.DatePicker;
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.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import static java.time.format.DateTimeFormatter.ofPattern;
@FacesConverter("br.com.jarch.faces.converter.localDateTimeConverter")
public class LocalDateTimeJsfConverter implements Serializable, Converter {
private static final long serialVersionUID = -482895881944630237L;
@Override
public LocalDateTime getAsObject(FacesContext arg0, UIComponent arg1, String value) {
if (value == null) {
return null;
}
try {
return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
} catch (Exception ex) {
try {
return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
} catch (Exception ex2) {
LocalDate localDate = LocalDate.parse(value, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
LocalTime localTime = LocalTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
return LocalDateTime.of(localDate, localTime);
}
}
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
if (value == null) {
return null;
}
String pattern = "";
if (Calendar.class.isAssignableFrom(uiComponent.getClass()))
pattern = ((Calendar)uiComponent).getPattern();
if (DatePicker.class.isAssignableFrom(uiComponent.getClass()))
pattern = ((DatePicker)uiComponent).getPattern();
if (pattern == null || pattern.isBlank())
pattern = "dd/MM/yyyy HH:mm:ss";
if (value instanceof Date) {
return new SimpleDateFormat(pattern).format(value);
}
LocalDateTime dateValue = (LocalDateTime) value;
return dateValue.format(ofPattern(pattern));
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy