SimpleDateFormat is buggy

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); String d = sdf.format(new Date(1465837275)); text2.setText(d); 

Must be 21:01

And I get. What the hell is that? 4:10

  • Where do you live? =) - Stranger in the Q
  • Yekaterinburg. Just before there were no problems with this, about 4 months ago when the code is - BluntHacker

1 answer 1

In your example, the date constructor from absolute time is used (conventionally speaking, the time is from the zone +0000 or GMT starting 1 января 1970 00:00:00 ). But when converting to string format, the time zone is not specified. Therefore, the default time zone is taken. As you can see from the online converter , it generally gives 23:10, but it indicates the time zone. If you need the 'right' time, then you should explicitly specify the time zone when converting. See example:

 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); Date date = new Date(1465837275); sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT-5")); System.out.println(sdf.format(date)); sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT+2")); System.out.println(sdf.format(date)); //обратный перевод с указанием выводить таймзону SimpleDateFormat sdf3 = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS z"); System.out.println(sdf3.format(date)); SimpleDateFormat sdf4 = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS Z"); System.out.println(sdf4.format(date)); SimpleDateFormat sdf5 = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS X"); System.out.println(sdf5.format(date)); 

Console output:

 04:10 21:10 17.01.1970 20:10:37.275 BRT 17.01.1970 20:10:37.275 -0300 17.01.1970 20:10:37.275 -03 

Details about the templates can be read in javadoc

  • date is taken from VK. Take a look out of VK - BluntHacker
  • I do not understand much about what vk is about here, but added an example in response - Temka is also
  • And what does the Date string look like that would store the zone in itself ?: - BluntHacker
  • It all depends on the template. Update the answer for clarification - Temka too