1

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

1 Answer 1

2

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.