Solution using java.time
, the modern API:
Your date-time string has timezone offset value and therefore, it's a candidate to be parsed into OffsetDateTime
object which you can convert to Instant
. The function, Instant#toEpochMilli
converts an instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM d H:m:s X u", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("Wed Feb 29 20:56:47 +0000 2012", dtf);
Instant instant = odt.toInstant();
long epochSecond = TimeUnit.SECONDS.convert(instant.toEpochMilli(), TimeUnit.MILLISECONDS);
System.out.println(epochSecond);
}
}
Output:
1330549007
Try to avoid performing calculations yourself if you have standard API available (e.g. TimeUnit#convert
used in the code above) to achieve what you would do with the calculation.
Learn more about java.time
, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.