You don't have to use DateFormat
for something as simple as this. You know what format the original date string is and you don't need a Date
object, you want a String
. Therefore, just convert it directly to String
(without creating an intermediate Date
object) as follows:
String s = "20120514045300.0Z"; String formatted = s.substring(0, 4) + '-' + s.substring(4, 6) + '-' + s.substring(6, 8) + "-T" + s.substring(8);
You can even use StringBuilder
as follows (although this is a bit inefficient due to copying the array):
StringBuilder sb = new StringBuilder(s); sb.insert(4, '-').insert(7,'-').insert(10,"-T"); String formatted = sb.toString();
source share