How can I convert time in unix timestamp to normal time?
-
1Your question is vague and ambiguous. Don't you just mean "How to convert a timestamp in (milli)seconds to a human readable time format of HH:mm:ss"? UTC is namely a timezone, as is GMT.BalusC– BalusC2010-08-13 02:15:32 +00:00Commented Aug 13, 2010 at 2:15
-
@BalusC that is incorrect GMT is GMT all the time, the British daylight savings time is BST which is GMT+1, GMT doesn't vary from UTC by anything more than negligible fractions of a second which aren't relevant in day to day use.delete me– delete me2010-08-13 02:18:16 +00:00Commented Aug 13, 2010 at 2:18
-
@MrXexxed: I edited the DST part away for the sake that.BalusC– BalusC2010-08-13 02:21:40 +00:00Commented Aug 13, 2010 at 2:21
-
@BalusC thanks, looks better now! But your point is valid, the questions title is misleading as for the purposes of this UTC and GMT are the same thing.delete me– delete me2010-08-13 02:26:42 +00:00Commented Aug 13, 2010 at 2:26
-
Title says mysql timestamp, question asks unix timestamp.Pramod Setlur– Pramod Setlur2018-11-06 22:49:11 +00:00Commented Nov 6, 2018 at 22:49
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().
Comments
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.