I tried everything could possibly think of to do this and have spent hours trying to figure it out..

I'm trying to take this timestamp: 2011-03-23 00:43:07 which is in GMT zimezone
and convert it to a Date that is in my timezone which is 4 hours later.

1. It has to be dynamic -- If I move to a different location (say one that is only 2 hours later), I shouldn't have to change the code.

2. I need to be able to get the ms time difference between then and now.

I did write something that's giving me a total headache, but I wont post it unless no one has a easy, strait way they can show me.

Recommended Answers

All 12 Replies

SimpleDateFormat with the TimeZone set to GMT, to parse the date, then simply display the date (without using the DateFormat object, or using a different one where you have not specifically set a TimeZone).

add 1/ not possibel, because java.util.Timestamp returns current time

add 2/

import java.awt.GridLayout;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TimeZoneSpinners {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TimeZoneSpinners().makeUI();
            }
        });
    }

    public void makeUI() {
        int offset = TimeZone.getDefault().getRawOffset();
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, Calendar.JUNE);
        cal.set(Calendar.YEAR, 2009);
        cal.set(Calendar.MONTH, Calendar.MARCH);
        cal.set(Calendar.DAY_OF_MONTH, 29);
        cal.set(Calendar.HOUR_OF_DAY, offset / (1000 * 60 * 60));
        cal.set(Calendar.MINUTE, (offset % (1000 * 60 * 60)) / (1000 * 60));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date date = cal.getTime();
        String[] zones = {"zulu", "Europe/London", "Etc/UTC", "Asia/Calcutta"};
        final JSpinner[] spinners = new JSpinner[zones.length];
        JPanel panel = new JPanel(new GridLayout(0, 1, 2, 2));
        ChangeListener listener = new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Object value = ((JSpinner) e.getSource()).getValue();
                for (JSpinner spinner : spinners) {
                    if (spinner != e.getSource()) {
                        spinner.setValue(value);
                    }
                }
            }
        };
        for (int i = 0; i < spinners.length; i++) {
            SpinnerDateModel model = new SpinnerDateModel();
            spinners[i] = new JSpinner(model);
            spinners[i].setBorder(new TitledBorder(zones[i]));
            SimpleDateFormat format = ((JSpinner.DateEditor) spinners[i].getEditor()).getFormat();
            format.setTimeZone(i == 0 ? new SimpleTimeZone(0, zones[i]) : TimeZone.getTimeZone(zones[i]));
            format.applyPattern("dd MMM yyyy, HH:mm");
            model.setValue(date);
            spinners[i].addChangeListener(listener);
            panel.add(spinners[i]);
        }
        JFrame frame = new JFrame();
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

that's not easy, Date&Time is complicated over at all

search for JODA time

You are making things far more complicated than they need to be. Date (and Timestamp) will always display the date in the local timezone, regardless of what timezone you used to parse the data, so "1" is not only possible, it is the default, and "2" (if really just needs the millisecond difference) is simply subtracting a getTime() call on that Date object from System.currentTimeMillis().

:-) some SQL Engines can do that...

a java.util.Date object only contains the anount of milliseconds since the Java Epoch, it doesn't contain any time zone informations at all, it doesn't use any local timeZone information in the construction, just the millisecond value

same I can see with java.sql.Timestamp for me returns current time, syncronized with some NetCurrentTimeProvider or not

maybe correct answer for OP would be look for Calendar instance (so little bit crypted thread) http://forums.oracle.com/forums/thread.jspa?threadID=2167355&start=0&tstart=0 , same as a few threads from your "homeForum"


Edit: hmmm maybe question, just why some topics about java.sql.Timestamp returns UTC Time, I think that isn't true, on my PC
1/ can't hold UTC
2/ don't want UTC/GTM, just GTM -1

String stamp = "2011-03-23 00:43:07";
      SimpleDateFormat dfZone = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss z");
      Date dZulu = dfZone.parse(stamp + " UTC");
      
      System.out.println(dfZone.format(dZulu)); // uses UTC
      
      dfZone.setTimeZone(TimeZone.getDefault());
      System.out.println(dfZone.format(dZulu)); // uses local time zone
      
      dfZone.setTimeZone(TimeZone.getTimeZone("PDT"));
      System.out.println(dfZone.format(dZulu)); // uses West Coast zone

:-)

it was on purpose, I waited so whether/if anyone else thought/noticed that, .... there are three equal TimeValue for different TimeZone

Sorry - typo - should be "PST" not "PDT" - its specified one way but displayed differently (why?)

hmmm ..... ???? each Java update has own/updated TimeZomes ????

I'll try it too, becuase I have instaled all meaningful JDK on my Comp, link that I sent contains example for that, I'm not sure maybe my shot to dark

edit: I think that I dont't understood Calendar instance correctly

between JDK (changes into IDE project properties) are some changes (halfHours TimeZone) but I can't reproduced your (maybe I don't full understood your) diffferencies

look like OP's lost ....

JamesCherrill, your example helped!

The only thing that needed to be changed was the 12hr clock to the 24hr clock by changing hh in the SimpleDateFormat to HH to get the correct ms difference from the Date instances (otherwise, sometimes it would show a 12 hr difference from each instance where there was none since AM and PM are not processed, nor given in the pattern).

try google with SimpleDateFormat

JamesCherrill, your example helped!

The only thing that needed to be changed was the 12hr clock to the 24hr clock by changing hh in the SimpleDateFormat to HH to get the correct ms difference from the Date instances (otherwise, sometimes it would show a 12 hr difference from each instance where there was none since AM and PM are not processed, nor given in the pattern).

OK, glad to help. Time to mark this particular problem as "solved"?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.