Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

Strange Java Timezone Date Conversion Problem

I want to convert ms-since-1970-timestamp to a date with timezone (Germany).

Here are two variants of code which worked - at least, I remember using it and it worked:

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 couldn't find the reason for a time-difference of 2hours.

It should be: 16:05:20 The code prints: 14:05:20 in both variants.

Could someone please help me and tell me what went wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the problem:

TimeZone.getTimeZone("Germany")

There's no such time zone ID, so Java in its infinite wisdom decides to just return you UTC without telling you that anything's wrong. Try this instead:

TimeZone.getTimeZone("Europe/Berlin")

Wikipedia has a list of IANA time zone IDs, but it's somewhat out of date (at the time of writing); the IANA data is the most up-to-date, but it's not as easily browsable...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...