Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Getting TimeZone instance from a date

With the following code-

    Timestamp ts = (Timestamp)results.get(0);
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");
    System.out.println(sdf.format(new Date(ts.getTime())));

I get output as: 04/29/2013 15:08:30 +0530

I wanted to create a TimeZone instance from the timestamp, so tried this-

    SimpleDateFormat FORMATTER = new SimpleDateFormat("Z");
    String tzString = FORMATTER.format(ts);

    // the tzString comes out to be +0530 (which is correct)

    TimeZone tz = TimeZone.getTimeZone(tzString);
    System.out.println(tz);

But the final TimeZone instance is of GMT as its not able to identify +0530.

So, how can I get a correct TimeZone instance here?

Upvotes: 1

Views: 170

Answers (4)

andyssundaypink
andyssundaypink

Reputation: 421

I tried this code below:

  Timestamp ts = new Timestamp(System.currentTimeMillis());

Then to get the TimeZone instance from the timestamp, I did this:

  SimpleDateFormat FORMATTER = new SimpleDateFormat("Z");
  TimeZone tzone = FORMATTER.getTimeZone();
  System.out.println(tzone.getDisplayName());
  System.out.println(tzone.getID());

I got:

Central European Time
Europe/Berlin

So I got my timezone which is +0200 instead of GMT.

Hope this is what you want.

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

You cannot get a TimeZone from a java.sql.Timestamp because it does not contain one. In your case you are simply getting your default TimeZone. It does not make sense. It is the same as TimeZone.getDefault();

Upvotes: 4

Rahul
Rahul

Reputation: 45060

Instead of using a SimpleDateFormat, you can simply do this:-

Calendar cal = Calendar.getInstance();
cal.setTime(new Date(ts.getTime()));
TimeZone tz = cal.getTimeZone();
System.out.println(tz);

Upvotes: 2

Duncan Jones
Duncan Jones

Reputation: 69339

Use a lowercase z in your pattern. That should return "GMT+0530", which will work.

Upvotes: 2

Related Questions