Strange java time zone date conversion problem
•
Java
I want to convert ms-since-1970-timestamp to a date with time zone (Germany)
These are two variations of the code – at least I remember using it, how it works:
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; public class TestDate { public static void main(String[] args) { Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("Germany"),Locale.GERMANY); Date d = new Date(); cal.setTime(d); System.out.println(String.format("%02d.%02d.%04d %02d:%02d:%02d",cal.get(Calendar.DAY_OF_MONTH),cal.get(Calendar.MONTH)+1,cal.get(Calendar.YEAR),cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),cal.get(Calendar.SECOND))); SimpleDateFormat df = new SimpleDateFormat( "dd.MM.yyyy HH:mm:ss.S" ); df.setTimeZone(TimeZone.getTimeZone("Germany")); System.out.println(df.format(d)); } }
It's really strange because I can't find the reason why the time is two hours short
It should be: 16:05:20 code printing: 14:05:20 two variants
Can someone help me and tell me what's wrong here?
Solution
This is the problem:
TimeZone.getTimeZone("Germany")
There is no such time zone ID, so Java's infinite wisdom decides to return only UTC without telling you what is wrong Replace with:
TimeZone.getTimeZone("Europe/Berlin")
Wikipedia has a list of IANA time zone IDS, but it is a little outdated (when writing); IANA data is the latest, but it is not so easy to browse
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码