Pergunta

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;
        }
Foi útil?

Solução

Don't do timezone math on the timestamp yourself. Instead, keep it in UTC and set the timezone on the 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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top