How can I convert time in unix timestamp to normal time?
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.
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.
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.
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.
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With