我有以下代码将GMT时间转换为本地时间,我从StackOverflow上的答案中获取了它,问题是该代码返回了错误的GMT时间值。

我的GMT时间是:+3,但是代码使用的是+2,我猜这是从我的设备获取GMT时间的时间,而我的设备的时间是+3 GMT。

这是代码:

        String inputText = "12:00";
    SimpleDateFormat inputFormat = new SimpleDateFormat
            ("kk:mm", Locale.US);
    inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat outputFormat =
            new SimpleDateFormat("kk:mm");
    // Adjust locale and zone appropriately
    Date date = null;
    try {
        date = inputFormat.parse(inputText);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String outputText = outputFormat.format(date);
    Log.i("Time","Time Is: " + outputText);


日志返回:14:00

最佳答案

这与您进行转换的日期有关。

您仅指定小时和分钟,因此计算是在1970年1月1日完成的。在该日期,大概您所在时区的GMT偏移量仅为2小时。

也指定日期。



SimpleDateFormat inputFormat =
    new SimpleDateFormat("kk:mm", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat outputFormat =
    new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

Date date = inputFormat.parse("12:00");

System.out.println("Time Is: " + outputFormat.format(date));




输出:

Time Is: 1970/01/01 12:00




显示夏令时/夏令时影响的其他代码:

SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat finlandFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
finlandFormat.setTimeZone(TimeZone.getTimeZone("Europe/Helsinki"));

SimpleDateFormat plus3Format = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
plus3Format.setTimeZone(TimeZone.getTimeZone("GMT+3"));

Date date = gmtFormat.parse("1970/01/01 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));

date = gmtFormat.parse("2016/04/22 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));


输出:

Time Is: 1970/01/01 12:00
Time Is: 1970/01/01 14:00 EET         <-- Eastern European Time
Time Is: 1970/01/01 15:00 GMT+03:00
Time Is: 2016/04/22 12:00
Time Is: 2016/04/22 15:00 EEST        <-- Eastern European Summer Time
Time Is: 2016/04/22 15:00 GMT+03:00

09-26 22:39
查看更多