Created
April 16, 2016 17:12
-
-
Save ankushs92/b72f48e5ffd4c1f27ffcc3a3265dcb0a to your computer and use it in GitHub Desktop.
Converting java.sql.timestamp to LocalDateTime and vice versa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Timestamp; | |
import java.time.LocalDateTime; | |
import javax.persistence.AttributeConverter; | |
import javax.persistence.Converter; | |
@Converter(autoApply = true) | |
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> { | |
@Override | |
public Timestamp convertToDatabaseColumn(LocalDateTime ldt) { | |
return Timestamp.valueOf(ldt); | |
} | |
@Override | |
public LocalDateTime convertToEntityAttribute(Timestamp ts) { | |
if(ts!=null){ | |
return ts.toLocalDateTime(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this will use the system default time zone. Alternative:
LocalDateTime.ofInstant(new Instant(ts), ZoneId.of("UTC"));