简体   繁体   English

如何将这种格式为“ 1394039043000”的SQL TimeStamp转换为字符串

[英]How to Convert SQL TimeStamp in this format “1394039043000” to String

I am using the method below but there is an hour difference in the converted timestamp 我正在使用下面的方法,但是转换后的时间戳有一个小时的差异

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;
        }

Don't do timezone math on the timestamp yourself. 不要自己在时间戳上进行时区数学运算。 Instead, keep it in UTC and set the timezone on the DateFormat . 而是将其保留在UTC中,并在DateFormat上设置时区。 For example: 例如:

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);

By default SimpleDateFormat uses timezone settings appropriate for the current default locale and that can explain the 1 hour difference you're seeing. 默认情况下, SimpleDateFormat使用适合当前默认语言环境的时区设置,这可以解释您所看到的1小时时差。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM