java - 为什么将本地时间转换为 GMT 时会出现差异?

标签 java android jodatime android-calendar

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


public class DefaultChecks {
    public static void main(String[] args) {

        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

        System.out.println("With Cal.."+dateFormatGmt.format(presentCal.getTime()));

        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

        String currentDateTimeString = dateFormatGmt.format(new Date());

        System.out.println("With format.."+currentDateTimeString);

    }
}

输出:

With Cal..2014-11-14T12:50:23.400Z
With format..2014-11-14T07:20:23.400Z

最佳答案

日期是一个瞬间,并且您的 TimeZone(s) 在两种格式调用之间是不同的。改成

    SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); // <-- here
    System.out.println("With Cal.."
            + dateFormatGmt.format(presentCal.getTime())); // <-- you use it 
                                                           // here.
    String currentDateTimeString = dateFormatGmt.format(new Date());
    System.out.println("With format.." + currentDateTimeString);

我在这里得到了正确的输出。

关于java - 为什么将本地时间转换为 GMT 时会出现差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26924919/

相关文章:

android - Android麦克风输入灵敏度

java - 按时区和小时偏移纪元日期 :minute

java - 分析远程大型堆转储

java - Android 无法解析 onPostExecute() 方法内的任何 AsyncTask 成员对象方法

java - 我正在尝试制作一个看起来像 PC 终端的基于文本的游戏,我找不到一种方法来告诉用户他们是否使用了错误的句子

java - 将 UTC 时间戳转换为其他时区特定时间

java - 如何在 Joda Time 中获取进度周期?

java - JSON解析问题

android - 如何让 EditText 提示不换行?

java - TextView 滚动不流畅