ThreeTenABP
The other answers are correct, but outdated before they were written. These days I recommend you use the modern Java date and time API known as JSR-310 or java.time
. Your date-time string format is ISO 8601, which the modern classes “understand” as their default.
Can you use the modern API on Android yet? Most certainly! The JSR-310 classes have been backported to Android in the ThreeTenABP project. All the details are in this question: How to use ThreeTenABP in Android Project.
long epochTime = OffsetDateTime.parse("2017-09-10T18:35:00+05:00")
.toInstant()
.getEpochSecond();
The result is 1505050500.
Edit: Arvind Kumar Avinash correctly points out in a comment: You do not need to convert an OffsetDateTime
to an Instant
to get the epoch seconds. You can simply use OffsetDateTime#toEpochSecond
.
Example of how to convert this into a human-readable date and time:
String formattedDateTime = Instant.ofEpochSecond(epochTime)
.atZone(ZoneId.of("Africa/Lusaka"))
.format(DateTimeFormatter.ofPattern("EEE, d MMMM h:mm a", Locale.ENGLISH));
This produces Sun, 10 September 3:35 PM
. Please provide the correct region and city for the time zone ID you want. If you want to rely on the device’s time zone setting, use ZoneId.systemDefault()
. See the documentation of DateTimeFormatter.ofPattern() for the letters you may use in the format pattern string, or use DateTimeFormatter.ofLocalizedDateTime()
for one of your locale’s default formats.