yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z' format

kushi picture kushi · May 16, 2017 · Viewed 10.2k times · Source

I am trying to convert GMT to IST.

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS");
  Date c= sdf.parse("2017-03-31T10:38:14.4723017Z");

  Date date = new Date();
  DateFormat istFormat = new SimpleDateFormat();
  DateFormat gmtFormat = new SimpleDateFormat();
  TimeZone gmtTime = TimeZone.getTimeZone("GMT");
  TimeZone istTime = TimeZone.getTimeZone("IST");

  istFormat.setTimeZone(gmtTime);
  gmtFormat.setTimeZone(istTime);
  System.out.println("GMT Time: " + istFormat.format(c));
  System.out.println("IST Time: " + gmtFormat.format(c));

My output is

GMT Time: 31/3/17 6:26 AM
IST Time: 31/3/17 11:56 AM

But my actual output should be

GMT Time: 31/3/17 5:08 AM
IST Time: 31/3/17 10:38 AM

What is wrong with my code?

Answer

Riaan Nel picture Riaan Nel · May 16, 2017

Milliseconds (SSS) can only be three digits. On more than that, the date rolls over - e.g. 10:38:14.1000 becomes 10:38:15.000. Add a couple of million milliseconds... and you get the behaviour that you're seeing now.

Try this.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date c = sdf.parse("2017-03-31T10:38:14.472Z");

System.out.println(c);

DateFormat istFormat = new SimpleDateFormat();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
TimeZone istTime = TimeZone.getTimeZone("IST");

istFormat.setTimeZone(gmtTime);
gmtFormat.setTimeZone(istTime);
System.out.println("GMT Time: " + istFormat.format(c));
System.out.println("IST Time: " + gmtFormat.format(c));