Convert Epoch time to date and Date to Epoch time in Android

Ramji picture Ramji · Jul 20, 2011 · Viewed 22.4k times · Source

StrDate = "2011-07-19T18:23:20+0000";

How can I get an epoch time for the above date format in android

also I would like to know how to convert a epoch time to the above date format.

I would appreciate a direct answer with an example.

Answer

Basil Bourque picture Basil Bourque · Dec 17, 2013

Example code using Joda-Time 2.3.

Unix time is number of seconds since beginning of 1970 in UTC/GMT.

How can I get an epoch time for the above date format in android

DateTime dateTimeInUtc = new DateTime( "2011-07-19T18:23:20+0000", DateTimeZone.UTC );
long secondsSinceUnixEpoch = ( dateTimeInUtc.getMillis() / 1000 ); // Convert milliseconds to seconds.

…and…

how to convert a epoch time to the above date format.

String dateTimeAsString = new DateTime( secondsSinceUnixEpoch * 1000, DateTimeZone.UTC ).toString();

To dump those values to the console…

System.out.println( "dateTimeInUtc: " + dateTimeInUtc );
System.out.println( "secondsSinceUnixEpoch: " + secondsSinceUnixEpoch );
System.out.println( "dateTimeAsString: " + dateTimeAsString );

Bonus: Adjust to another time zone.

DateTime dateTimeMontréal = dateTimeInUtc.withZone( DateTimeZone.forID( "America/Montreal" ) );