Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL timestamp to Java date conversion

Tags:

java

mysql

jdbc

How can I convert time in unix timestamp to normal time?

like image 294
JJunior Avatar asked Aug 13 '10 02:08

JJunior


People also ask

Can we convert timestamp to date in Java?

Timestamp class can be converted to Date class in java using the Date class which is present in Java. Util package. The constructor of the Date class receives a long value as an argument.

How do I convert timestamp to date?

In Java, TimeStamp can be converted into Date using the constructor of the Date class of the java. util package. It must be noted that Date class takes an argument as a long value hence the TimeStamp object needs to be converted into long. This is done using the getTime() method of Timestamp class of the java.

How do I convert a timestamp to a date in sql?

To record a date or time, use a datetime2 data type. So you cannot convert a SQL Server TIMESTAMP to a date/time - it's just not a date/time. But if you're saying timestamp but really you mean a DATETIME column - then you can use any of those valid date formats described in the CAST and CONVERT topic in the MSDN help.

How do I convert a timestamp to a String in Java?

The toString() method of the java. sql. Timestamp class returns the JDBC escape format of the time stamp of the current Timestamp object as String variable. i.e. using this method you can convert a Timestamp object to a String.


2 Answers

Your question is vague and ambiguous. I'll leave the timezone ambiguity away.

How can I convert time in unix timestamp to normal time?

I suspect that you're somehow obtaining a long or maybe a String value from the DB instead of a Date. In JDBC, you would normally like to use the appropriate methods to obtain the DB-specific datatypes. The MySQL TIMESTAMP datatype can be obtained by ResultSet#getTimestamp() which gives you a java.sql.Timestamp which in turn is a subclass of java.util.Date.

In a nut, the following should do:

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

To format it further in a human readable format whenever you're going to present it to the enduser, use SimpleDateFormat. Click the link, it contains an overview of all patterns. Here's an example:

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

To do all the other way round, use respectively SimpleDateFormat#parse() and PreparedStatement#setTimestamp().

like image 86
BalusC Avatar answered Sep 21 '22 15:09

BalusC


Unix timestamp is seconds since "epoch". Java's currentTimeMillis are milliseconds since "epoch". You can get a Java Date object with a simple multiplication like this:

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

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

like image 24
Thilo Avatar answered Sep 21 '22 15:09

Thilo