Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@DateTimeFormat with daylight saving error when converting

I am having a problem converting a date that actually does not exists using the @DateTimeFormat annotation.

For example, when I set the date 15/10/2017, with annotation in my entity being as follows:

@Column(nullable = false)
@NotNull
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dataVisita;

I receive the error:

Failed To Convert Property Value Of Type Java.Lang.String To Required Type Java.Util.Date For Property DataVisita; 
Nested Exception Is Org.Springframework.Core.Convert.ConversionFailedException: 
    Failed To Convert From Type Java.Lang.String To Type @Javax.Persistence.Column @Javax.Validation.Constraints.NotNull @Org.Springframework.Format.Annotation.DateTimeFormat Java.Util.Date For Value 15/10/2017; 
Nested Exception Is Java.Lang.IllegalArgumentException: 
    Cannot Parse "15/10/2017": Illegal Instant Due To Time Zone Offset Transition (America/Sao_Paulo)

I understand that the error tells me that the date 15/10/2017 00:00:00 does not actually exists, but I want to convert to 15/10/2017 01:00:00, ignoring this way the problem and finding the correspondent date.

Is there a way for me to override the @DateTimeFormat annotation or a way to point the formatter to be lenient?

like image 959
Thiesen Avatar asked Oct 16 '17 20:10

Thiesen


1 Answers

Try this:

@Column(nullable = false)

@NotNull

@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")

private Date dataVisita;

It seems to do what you want (adjust 0:00 to 1:00), you'll need to implement a validator as follows:

public class PersonValidator implements Validator {

    /**
     * This Validator validates *just* Person instances
     */
    public boolean supports(Class clazz) {
        return Date.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        String dateString = (String) obj;
        DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
        DateTime ourDate = null;
        try {
            fmt.parseDateTime(dateString);
        } catch (IllegalArgumentException e) {
            // massage your hour here
        } finally {
            ourDate = fmt.parseDateTime(dateString);
        }
    }
}
like image 192
hd1 Avatar answered Oct 12 '22 03:10

hd1