Johan
Johan

Reputation: 35194

Apply timezone to Date object

    Date now = new Date();
    Date then = new Date((long)obj.timestamp*1000);

    TimeZone tz = TimeZone.getDefault();

Not very familiar with java, but is there any way to apply a timezone to a Date object? I found this thread, but this is about Calendar timezones, which i believe is something different?

Upvotes: 4

Views: 13906

Answers (3)

PermGenError
PermGenError

Reputation: 46428

use SimpleDateFormat.setTimeZone(TimeZone) to set TimeZone.

    SimpleDateFormat sdf = new SimpleDateFormat("yourformat");   
    TimeZone tz = TimeZone.getDefault(); 
    sdf.setTimeZone(tz);
    sdf.format(yourdate); //will return a string rep of a date with the included format

Upvotes: 2

Khantahr
Khantahr

Reputation: 8528

Date objects do not have a timezone, it is simply a container for a specific moment in time. If you want to apply a timezone to it, you'll have to use a Calendar. I do it as follows

Calendar cal = Calendar.getInstance();
cal.setTime( date );

If you're just looking to display the Date adjusted for a timezone, then you can use SimpleDateFormat to apply the proper timezone adjustments.

Upvotes: 2

Yogendra Singh
Yogendra Singh

Reputation: 34367

Date object uses the current timezone by default. If you are trying to print the time in specific timezone, you may use SimpleDateFormat as below:

   //put the desired format      
   DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy hh:mm:ss Z");
   //set the desired timezone
   formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));

   String formattedNowInTimeZone  = formatter.format(now);
   String formattedThenInTimeZone  = formatter.format(then);

Upvotes: 3

Related Questions