android - 如何将这种格式的 SQL 时间戳 "1394039043000"转换为字符串

标签 android timestamp simpledateformat

我正在使用下面的方法但是转换后的时间戳有一个小时的差异

public static String getServerFormattedDate(String dateStr) {


    Timestamp ts = new Timestamp(Long.valueOf(dateStr)); // input date in
                                                                    // Timestamp
                                                                    // format

            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");

            Calendar cal = Calendar.getInstance();
            cal.setTime(ts);
            cal.add(Calendar.HOUR, +7); // Time different between UTC and PDT is +7
                                        // hours
            String convertedCal = dateFormat.format(cal.getTime()); // This String
                                                                    // is converted
                                                                    // datetime
            /* Now convert String formatted DateTime to Timestamp */

            return convertedCal;
        }

最佳答案

不要自己对时间戳进行时区计算。相反,将其保存为 UTC 并在 DateFormat 上设置时区。例如:

SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("PDT"));
Date date = new Date(Long.valueOf(dateStr));
String convertedCal = dateFormat.format(date);

默认情况下,SimpleDateFormat 使用适合当前默认语言环境的时区设置,这可以解释您看到的 1 小时差异。

关于android - 如何将这种格式的 SQL 时间戳 "1394039043000"转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22346676/

相关文章:

android - 如何通过无线 LAN 网络接收传入消息并启动 Web 浏览器?

android - 如何在 recyclerview viewholder 中处理大量不同的 View 类型

java - 将毫秒转换为 UTC 时间戳

voip - 如何计算RTP中的有效时间偏移量

android - 构建 Ionic App 时找不到模块 'shelljs'

android - 调用 retrofit.Call<> 时出现 NullPointerException

python - 将 EPOCH 时间戳转换为日期

java - 如何在Java(android)中自定义SimpleDateFormat()的日期格式?

java - Java(或 Android)中的日期格式

java - 设置输入日期并将其添加到列表