16

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?

iandotkelly
  • 9,024
  • 8
  • 48
  • 67
Ranco
  • 893
  • 2
  • 13
  • 43

2 Answers2

29

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.

bart
  • 1,003
  • 11
  • 24
Luis
  • 11,978
  • 3
  • 27
  • 35
  • You are missing the year in your comment, but that's the format I used in the code above. – Luis Nov 23 '12 at 12:00
  • I used your format string and was getting different results in JS and Java. It should be `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'` – OhhhThatVarun Oct 11 '22 at 09:49
11

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

falconforce
  • 140
  • 1
  • 5
  • 2
    FYI: Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 24 '18 at 01:18