Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert java.sql.timestamp to LocalDate (java8) java.time?

People also ask

How do I get a Timestamp from LocalDate?

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

How do I get LocalDate in Java 8?

LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date.

How do I cast Java SQL Timestamp to Java Lang string?

String dateString = "2016-02-03 00:00:00.0"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss. S"). parse(dateString); String formattedDate = new SimpleDateFormat("yyyyMMdd"). format(date);


You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.


The accepted answer is not ideal, so I decided to add my 2 cents

timeStamp.toLocalDateTime().toLocalDate();

is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

The good solution is

timestamp.toInstant().atZone(zoneId).toLocalDate()

Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

The general approach should be

  1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
  2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.

You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:

public static void main(String... args) {
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    TimeZone.setDefault(utcTimeZone);
    ...
    timestamp.toLocalDateTime().toLocalDate();
}

Or you can use toInstant.atZone chain:

timestamp.toInstant()
        .atZone(ZoneId.of("UTC"))
        .toLocalDate();