I should like to contribute the modern answer. This isn’t the answer you asked for, but I hope it’s the answer you want.
ThreeTenABP
SimpleDateFormat
and Date
are long outdated. I can understand why you are still trying to use them on Android, because Android Java 7 comes with nothing better built-in. However, this is a good time for you to learn to use an external library. I recommend you use ThreeTenABP, it offers you the modern Java date and time API, which is much nicer to work with than the outdated classes.
For how to include that library with your project, there is a wonderful explanation in this question: How to use ThreeTenABP in Android Project.
Then the code could be for instance:
long unixTimestamp = LocalDate.parse("1986-10-02")
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.getEpochSecond();
int intValue;
if (unixTimestamp <= Integer.MAX_VALUE) {
intValue = (int) unixTimestamp;
System.out.println(intValue);
} else {
System.out.println("int overflow; cannot represent " + unixTimestamp + " in an int");
}
This prints:
528595200
This is the value you asked for. There seems to be no need to use the time zone of GMT+10 that you tried in your question (I tried, and got the wrong result).
Unix timestamp in an int
Unix timestamps can be represented in 32-bit int
until some time in January 2038, after that you will have a kind of “year 2000 problem”. So I guess we might as well get used to using 64-bit long
instead.
What went wrong?
For the code in your question, you may have a couple of problems (apart from using the outdated classes):
- The compiler requires you to take the possibility of a
ParseException
into account, either by declaring that your method may throw it, or by surrounding your code with a try
/catch
construct. Read up on exception handling in Java to learn more, it’s described in a gazillion places.
- You multiplied by
1000L
instead of dividing by it, thereby overflowing the Integer
you tried to store your result into afterwards.
- Finally, as I said, you should use
TimeZone.getTimeZone("GMT")
without +10
.