1

I need a java.sql.Timestamp but when I try to convert from LocalDateTime, it fails because when the input string was converted to LocalDateTime, the letter "T" was added, as in 2013-03-15T00:00:00.000. Any ideas? Or is there a better way to convert a string to a Timestamp? I just wanted to use joda in case the time needs to be manipulated in the future.

Thanks.

yellavon
  • 2,821
  • 12
  • 52
  • 66
  • Are you using an ORM framework? Normally you wouldn't explicitly convert to a `java.sql` type, but let the framework do it for you. – Zutty Mar 15 '13 at 13:11

2 Answers2

7

Why can't you do

LocalDateTime ldt  = LocalDateTime.now();
Timestamp ts = new Timestamp(ldt.toDate().getTime());
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    Yeah that works, it was an unrelated bug in my code. :( Also `Timestamp ts = new Timestamp(ldt.toDateTime().getMillis());` works as well. Any advantage of one to the other? – yellavon Mar 15 '13 at 13:37
  • I think both are same – Arun P Johny Mar 15 '13 at 14:55
  • I verified both ways produce the same output in millis. The middle state (`.toDate()` or `to.DateTime()` are just different formats. – yellavon Mar 16 '13 at 18:46
  • Joda Time Javadoc has this to say: "Converting to a JDK Date is full of complications as the JDK Date constructor doesn't behave as you might expect around DST transitions. This method works by taking a first guess and then adjusting. This also handles the situation where the JDK time zone data differs from the Joda-Time time zone data." Based on that I would presume `toDateTime()` is more accurate in such circumstances. – Hendy Irawan Jul 19 '13 at 09:54
1

The best way use Java 8 time API:

  LocalDateTime ldt = timeStamp.toLocalDateTime();
  Timestamp ts = Timestamp.valueOf(dateTime);

For use with JPA put in with your model (https://weblogs.java.net/blog/montanajava/archive/2014/06/17/using-java-8-datetime-classes-jpa):

@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) {
        return ts.toLocalDateTime();
    }
}

So now it is relative timezone independent time. Additionally it is easy do:

  LocalDate ld = ldt.toLocalDate();
  LocalTime lt = ldt.toLocalTime();

Formatting:

 DateTimeFormatter DATE_TME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
 String str = ldt.format(DATE_TME_FORMATTER);
 ldt = LocalDateTime.parse(str, DATE_TME_FORMATTER);
Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197