Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java.time.LocalDateTime SE 8 to timestamp [duplicate]

How do you convert a Localdatetime to timestamp? I want to use the new SE 8 date api because it is better than the util date and calendar. I plan to use localdatetime throughout my program and then place that date into a mysql database. I have looked for an answer but there doesn't seem to be very many questions and answers for java.time. This is a little of the code that I am testing. This is as far as I got.

        LocalDateTime c = LocalDateTime.now();

        java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.getLong());

I think I need to convert it into a long first, but I don't know how. The api allows for converting individual elements like month and day, but not for the whole date. Since I'm already here, how do you convert back from timestamp? Should I just use jodatime?

I tried this:

 LocalDateTime c = LocalDateTime.now();
 ZoneId zoneId = ZoneId.systemDefault();

 System.out.println("this:" + c);

 java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.atZone(zoneId).toEpochSecond());

 pst.setTimestamp(2, javaSqlDate);

This only saves the date around 1970. The system.print prints the current date correctly. I want it to save the current date.

like image 714
Josiah L. Avatar asked Jun 29 '15 08:06

Josiah L.


2 Answers

LocalDateTime l = LocalDateTime.now();
Timestamp t = Timestamp.valueOf(l);

Source: https://coderanch.com/t/651936/databases/Convert-java-time-LocalDateTime-SE

like image 159
Wilson Ferro Avatar answered Oct 17 '22 07:10

Wilson Ferro


First of all, you should decide if you really want to use LocalDateTime. Below are some explanations about the difference, taken from here:

<...> LocalDateTime is not a point on the time line as Instant is, LocalDateTime is just a date and time as a person would write on a note. Consider the following example: two persons which were born at 11am, July the 2nd 2013. The first was born in the UK while the second in California. If we ask any of them for their birth date it will look that they were born on the same time (this is the LocalDateTime) but if we align the dates on the timeline (using Instant) we will find out that the one born in California is few hours younger than the one born in the UK (NB: to create the appropriate Instant we have to convert the time to UTC, this is where the difference lays).<...>

In order to get long from Instant you could use getEpochSecond() method.

In order to get long from LocalDateTime you should provide a timezone.

like image 37
hammelion Avatar answered Oct 17 '22 08:10

hammelion