Convert LocalDate to LocalDateTime or java.sql.Timestamp

I am using JodaTime 1.6.2.

I have a LocalDate that I need to convert either to (Joda) LocalDateTime , or to java.sqlTimestamp for ormapping.

The reason for this is because I figured out how to convert between LocalDateTime and a java.sql.Timestamp :

 LocalDateTime ldt = new LocalDateTime(); DateTimeFormatter dtf = DateTimeFormatter.forPattern("yyyy-MM-dd HH:mm:ss"); Timestamp ts = Timestamp.valueOf(ldt.toString(dtf)); 

So, if I can just convert between LocalDate and LocalDateTime , then I can do a continuous conversion in java.sql.Timestamp . Thanks for any pushing in the right direction!

+92
java timestamp jodatime
Jan 24 '12 at 18:46
source share
6 answers

Jodatime

To convert JodaTime org.joda.time.LocalDate to org.joda.time.LocalDate just do

 Timestamp timestamp = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis()); 

To convert JodaTime org.joda.time.LocalDateTime to org.joda.time.LocalDateTime just do

 Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis()); 



Javatime

To convert Java8 java.time.LocalDate to java.time.LocalDate just do

 Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay()); 

To convert Java8 java.time.LocalDateTime to java.time.LocalDateTime just do

 Timestamp timestamp = Timestamp.valueOf(localDateTime); 
+208
Jan 24 2018-12-12T00:
source share

The best way to use the Java 8 time API:

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

To use with JPA, enter 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 this is relative time dependent time. In addition, it is easy to 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); 

UPDATE: postgres 9.4.1208, HSQLDB 2.4.0, etc. Understand the Java 8 Time API without any conversation!

+42
Jan 07 '15 at 21:54
source share

TL; dr

The Joda-Time project is in maintenance mode, now superseded by java.time classes.

  • Just use the java.time.Instant class.
  • Not necessary:
    • LocalDateTime
    • java.sql.Timestamp
    • Strings

Capture the current moment in UTC.

 Instant.now() 

To save this point in the database:

 myPreparedStatement.setObject( … , Instant.now() ) // Writes an 'Instant' to database. 

To extract this point from the database:

 myResultSet.getObject( … , Instant.class ) // Instantiates a 'Instant' 

To adjust the time of the wall clock in relation to a specific time zone.

 instant.atZone( z ) // Instantiates a 'ZonedDateTime' 

LocalDateTime - invalid class

Other answers are correct, but they do not indicate that LocalDateTime is the wrong class for your purpose.

In both java.time and Joda-Time, LocalDateTime intentionally devoid of any concept of time zone or offset from UTC. Thus, this does not represent a moment and is not a point on the timeline. LocalDateTime is an approximation of potential moments in the range of about 26-27 hours.

Use LocalDateTime for either when the zone / offset is unknown (not a good situation), or when the zone uncertainty is uncertain. For example, β€œChristmas begins at the first moment of December 25, 2018” will be presented as LocalDateTime .

Use ZonedDateTime to represent a moment in a specific time zone. For example, Christmas starting in any particular zone, such as Pacific/Auckland or America/Montreal , will be represented by a ZonedDateTime object.

For a moment, always in UTC use Instant .

 Instant instant = Instant.now() ; // Capture the current moment in UTC. 

Timezone application. The same moment, the same point on the timeline, but viewed with a different wall clock time.

 ZoneId z = ZoneId.of( "Africa/Tunis" ) ; ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time. 

So, if I can just convert between LocalDate and LocalDateTime,

No, the wrong strategy. If you only have a date value and you want to enter a date-time, you must specify the time of day. This time of day may not be valid on this date for a specific zone - in this case, the ZonedDateTime class automatically adjusts the time of day as necessary.

 LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ; LocalTime lt = LocalTime.of( 14 , 0 ) ; // 14:00 = 2 PM. ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ; 

If you want the first moment of the day to be your time of day, let java.time determine that moment. Do not think that the day starts at 00:00:00. Anomalies, such as daylight saving time (DST), mean that the day can start at another time, for example, 01:00:00.

 ZonedDateTime zdt = ld.atStartOfDay( z ) ; 

java.sql.Timestamp is the wrong class

java.sql.Timestamp is part of the problematic old time classes, which are now obsolete, are completely superseded by the java.time classes. This class was used to represent the moment in UTC with a resolution of nanoseconds . This target is now used with java.time.Instant .

JDBC 4.2 with getObject / setObject

Starting with JDBC 4.2 and later, your JDBC driver can directly exchange java.time objects with the database by calling:

For example:

 myPreparedStatement.setObject( … , instant ) ; 

… as well as …

 Instant instant = myResultSet.getObject( … , Instant.class ) ; 

Modern Heritage Transformation

If you must interact with old code that has not yet been updated to java.time, convert back and forth using the new methods added to the old classes.

 Instant instant = myJavaSqlTimestamp.toInstant() ; // Going from legacy class to modern class. 

…as well as…

 java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( instant ) ; // Going from modern class to legacy class. 



About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old obsolete time classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises switching to the java.time classes.

To learn more, check out the Oracle tutorial . And search for qaru for many examples and explanations. The specification is JSR 310 .

You can exchange java.time objects directly with your database. Use a JDBC driver compatible with JDBC 4.2 or later. No strings needed, no java.sql.* Needed.

Where can I get java.time classes?

  • Java SE 8 , Java SE 9 and later
    • Built in.
    • Part of the standard Java API with integrated implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the functionality of java.time is included back in Java 6 and 7 in ThreeTen-Backport .
  • Android
    • Later versions of the Android package implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts the ThreeTen-Backport (mentioned above). See How to use ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and others .

+8
Mar 12 '18 at 23:35
source share

Depending on your time zone, you may lose a few minutes (1650-01-01 00:00:00 will be 1649-12-31 23:52:58)

Use the following code to avoid this.

 new Timestamp(localDateTime.getYear() - 1900, localDateTime.getMonthOfYear() - 1, localDateTime.getDayOfMonth(), localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(), localDateTime.getSecondOfMinute(), fractional); 
+5
Apr 10 '12 at 23:12
source share

Since Joda fades away, someone may want to convert LocaltDate to LocalDateTime in Java 8. In Java 8, LocalDateTime will allow you to instantiate LocalDateTime using LocalDate and LocalTime . Check here.

public static LocalDateTime (LocalDate date, LocalTime time)

The sample will be

  // just to create a sample LocalDate DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd"); LocalDate ld = LocalDate.parse("20180306", dtf); // convert ld into a LocalDateTime // We need to specify the LocalTime component here as well, it can be any accepted value LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00 

For reference, in order to use the era of seconds below,

  ZoneId zoneId = ZoneId.systemDefault(); long epoch = ldt.atZone(zoneId).toEpochSecond(); // If you only care about UTC long epochUTC = ldt.toEpochSecond(ZoneOffset.UTC); 
+2
Mar 12 '18 at 9:55
source share

Java8 +

 import java.time.Instant; Instant.now().getEpochSecond(); //timestamp in seconds format (int) Instant.now().toEpochMilli(); // timestamp in milliseconds format (long) 
0
Dec 05 '18 at 7:00
source share



All Articles