Skip to content

Instantly share code, notes, and snippets.

@nickrussler
Created November 18, 2013 13:39
Show Gist options
  • Star 60 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save nickrussler/7527851 to your computer and use it in GitHub Desktop.
Save nickrussler/7527851 to your computer and use it in GitHub Desktop.
Convert Date String to/from ISO 8601 respecting UTC in Java
public static String toISO8601UTC(Date date) {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
return df.format(date);
}
public static Date fromISO8601UTC(String dateStr) {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
try {
return df.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
@octohub
Copy link

octohub commented Jun 2, 2017

Thank you for this, very helpful.

@Huynhtri027
Copy link

Thank you for this, very helpful.

@Fakher-Hakim
Copy link

Thanks a lot !

@phaniDPK
Copy link

+1
Thanks for the snippet

@FSPinho
Copy link

FSPinho commented Apr 26, 2018

+1

@okiwicaksono
Copy link

Thanks for the gist

@akash-suresh
Copy link

+1

@myr4ik07
Copy link

Дякую

@karanalang
Copy link

+1

@MohammadAdib
Copy link

Thank you!

@AKryukov92
Copy link

Found this while googling "java date parse from utc". Other answers usually don't set timezone for SimpleDateFormat.

@AnaFeuvrier
Copy link

thank you very much

@nicenemo
Copy link

nicenemo commented Feb 6, 2020

df.setTimeZone(...) thanks

@ahmadalibaloch
Copy link

Why we need to set timezone. Things are working perfectly without it.

@adamoBMX
Copy link

adamoBMX commented May 23, 2022

Thanks, life saver. Someday I'll get my project off the Calendar/Date classes!

@vpokrityuk
Copy link

Гарно дякую)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment