I can convert a unix timestamp to a Date() object by putting the long value into the Date() constructor. For eg: I could have it as new Date(1318762128031).
But after that, how can I get back the unix timestamp from the Date() object?
I can convert a unix timestamp to a Date() object by putting the long value into the Date() constructor. For eg: I could have it as new Date(1318762128031).
But after that, how can I get back the unix timestamp from the Date() object?
getTime() retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.
getTime() = unixTimestamp * 1000), getTime() would always return three Zeros at the end, but in fact can return anything from ending with 000 to 999, which means it has a higher precision due to milliseconds and is not just "*1000". Meaning: Comparing a real unixTimestamp*1000 with the getTime() result would only succeed in ~0.1% of the cases.To get a timestamp from Date(), you'll need to divide getTime() by 1000, i.e. :
Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691
or simply:
long unixTime = System.currentTimeMillis() / 1000L;
new Date().getTime()import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Timeconversion {
private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH); //Specify your locale
public long timeConversion(String time) {
long unixTime = 0;
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:30")); //Specify your timezone
try {
unixTime = dateFormat.parse(time).getTime();
unixTime = unixTime / 1000;
} catch (ParseException e) {
e.printStackTrace();
}
return unixTime;
}
}
In java 8, it's convenient to use the new date lib and getEpochSecond method to get the timestamp (it's in second)
Instant.now().getEpochSecond();
Instant instead of Instant.now(). Or yourDesiredJavaUtilDate.toInstant() if you got an old-fashioned Date from a legacy API.java.time.Instant
.ofEpochMilli( 1_318_762_128_031L ) // From count to moment.
.toEpochMilli() // From moment to count.
1318762128031
In Java 8+, use the java.time classes.
Never use the terribly flawed legacy classes, such as Date, Calendar, SimpleDateFormat, Timestamp, etc.
You apparently have a count of milliseconds since the epoch reference of the first moment of 1970 in UTC, 1970-01-01T00:00Z.
I could have it as new Date(1318762128031)
Instant instant = Instant.ofEpochMilli( 1_318_762_128_031L ) ;
Generate text in standard ISO 8601 format.
String output = instant.toString() ;
Run this code at Ideone.com.
2011-10-16T10:48:48.031Z
You said:
how can I get back the unix timestamp from the Date() object?
Interrogate the Instant object.
long count = instant.toEpochMilli() ;
We get the same long number as where we started.
1318762128031