Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android time in iso 8601

using android and joda time lib - the I am trying to convert the user's timezone in order to format it later to : 2012-11-12T21:45:00+02:00 for example.

DateTimeZone zone = DateTimeZone.forID( TimeZone.getDefault().getID());

the above code fails - anyone know how can I take "Europe/London" (Timezone.getID) and convert it to an offset so I can put it in ISO 8601 format?

like image 542
Ranco Avatar asked Nov 22 '12 14:11

Ranco


People also ask

What time is it in ISO 8601?

UTC time in ISO-8601 is 17:56:33Z.

Is ISO 8601 always UTC?

Date.prototype.toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .

Does ISO 8601 include timezone?

Time zone designators. Time zones in ISO 8601 are represented as local time (with the location unspecified), as UTC, or as an offset from UTC.


2 Answers

If I have correctly understood your objective you can use directly the SimpleDateFormat class.

Example code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.UK);
String formattedDate = sdf.format(new Date());

You can see documentation in SimpleDateFormat

Regards.

like image 129
Luis Avatar answered Oct 13 '22 19:10

Luis


API level 26 added support for many time and date classes from Java. So this solution can now also be applied: https://stackoverflow.com/a/25618897/3316651

// works with Instant
Instant instant = Instant.now();
System.out.println(instant.format(DateTimeFormatter.ISO_INSTANT));

// works with ZonedDateTime 
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt.format(DateTimeFormatter.ISO_INSTANT));

// example output
2014-09-02T08:05:23.653Z

Credits to JodaStephen.

Android doc: https://developer.android.com/reference/java/time/format/DateTimeFormatter.html#ISO_INSTANT

like image 26
falconforce Avatar answered Oct 13 '22 19:10

falconforce