问题
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?
回答1:
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));
回答2:
Have you tried changing the format to "yyyy-MM-dd'T'HH:mm:ss.sssssssZ"
?
Also, when you type Z
in your Date object, you should write the time zone designator, for example, "2017-03-31T10:38:14.4723017+01:00".
来源:https://stackoverflow.com/questions/44000755/yyyy-mm-ddthhmmss-sssssssz-format