MySQL timestamp for date conversion in Java

How can I convert time to a standard unix timestamp?

+3
java mysql jdbc
Aug 13 '10 at 2:11
source share
2 answers

Your question is fuzzy and ambiguous. I will leave the time zone uncertainty.

How can I convert time to a standard unix timestamp?

I suspect you are somehow getting a long value or maybe String from the database instead of Date . In JDBC, you would usually like to use the appropriate methods to get database-specific data types. The MySQL TIMESTAMP data TIMESTAMP can be obtained by ResultSet#getTimestamp() , which gives you java.sql.Timestamp , which in turn is a subclass of java.util.Date .

The following should be done in the nut:

 Date date = resultSet.getTimestamp("columnname"); 

To format it further in a human readable format, whenever you intend to present it to the end user, use SimpleDateFormat . Click the link that provides an overview of all the templates. Here is an example:

 String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date); 

To do the opposite, use SimpleDateFormat#parse() and PreparedStatement#setTimestamp() .

+18
Aug 13 2018-10-10T00:
source share

Unix timestamps are seconds from the era. Java currentTimeMillis is milliseconds since the "era". You can get a Java Date object with simple multiplication as follows:

  Date dateFromUnixTime = new Date( 1000l * unixTime) ; 

From there, you can format it using the usual date formatting tools in Java.

+1
Aug 13 2018-10-10T00:
source share



All Articles