Jim
Jim

Reputation: 19552

How can I get time from specific timezone?

I have a timezone and I do:

TimeZone tz = TimeZone.getTimeZone("GMT-05:00”); Calendar c = Calendar.getInstance(tz);

How can I get a DateTime object with the correct time from this timezone?
If I do c.getTime() I get the current time and not that timezone’s time.
Doing

String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
            String.format("%02d" , c.get(Calendar.MINUTE))+":"+
.                   String.format("%02d" , c.get(Calendar.SECOND))+":"+
    .           String.format("%03d" , c.get(Calendar.MILLISECOND));

I get the expected time but I can not create a valid DateTime object from this string.
How can I solve this?

Upvotes: 1

Views: 2185

Answers (4)

krazy
krazy

Reputation: 347

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// GMT-5
df.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
String strDate = df.format(date);
System.out.println("Date and time in GMT-5: " + strDate);

Upvotes: 1

Hemant Ukey
Hemant Ukey

Reputation: 328

This can be helpful see this link

TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
Calendar c = Calendar.getInstance(tz);
String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
            String.format("%02d" , c.get(Calendar.MINUTE))+":"+
.                   String.format("%02d" , c.get(Calendar.SECOND))+":"+
    .           String.format("%03d" , c.get(Calendar.MILLISECOND));

Upvotes: 0

You need to use the DateTime.WithZone method

TimeZone timeZone = TimeZone.getTimeZone("GMT-05:00");
    DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(timeZone);
    System.out.println(timeZone);
    System.out.println(dateTimeZone);
    DateTime dt = new DateTime();
    DateTime dtLondon = dt.withZone(dateTimeZone);
    System.out.println(dtLondon);

Upvotes: 0

rodolk
rodolk

Reputation: 5907

Other possibility to obtain and print time with time zone included:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class TestDate {

    public static void main(String[] args){
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String dateString = df.format(date);

        System.out.println(dateString);
    }
}

Upvotes: 0

Related Questions