Skip to content

Instantly share code, notes, and snippets.

@ankushs92
Created April 16, 2016 17:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankushs92/b72f48e5ffd4c1f27ffcc3a3265dcb0a to your computer and use it in GitHub Desktop.
Save ankushs92/b72f48e5ffd4c1f27ffcc3a3265dcb0a to your computer and use it in GitHub Desktop.
Converting java.sql.timestamp to LocalDateTime and vice versa
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;
}
}
@nmatpt
Copy link

nmatpt commented Dec 17, 2016

Note that this will use the system default time zone. Alternative: LocalDateTime.ofInstant(new Instant(ts), ZoneId.of("UTC"));

@kimgy0
Copy link

kimgy0 commented Sep 14, 2021

Good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment