tyczj
tyczj

Reputation: 73856

Converting a date string from a timezone to different time zone

I have a date that I get from a server formatted in EST like this

05/07/2012 16:55:55 goes month/day/year then time

if the phone is not in EST how can I convert it to the timezone the phone is in?

it would be not problem if I got the time in milliseconds but I dont

EDIT:

ok now the time is not correct when formatting

                String sTOC = oNewSTMsg.getAttribute("TOC").toString();
                String timezoneID = TimeZone.getDefault().getID();
                DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
                format.setTimeZone(TimeZone.getTimeZone("EST"));
                String newtimezoneID = TimeZone.getDefault().getID();
                Date timestamp = null;
                try{
                    timestamp = format.parse(sTOC);
                    format.setTimeZone(TimeZone.getDefault());
                    timezoneID = format.format(timestamp);
                }catch(ParseException e){

                }

I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?

Upvotes: 0

Views: 1611

Answers (2)

wattostudios
wattostudios

Reputation: 8774

Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html

You can then create a Calendar for the Date...

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

And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()

Using the Calendar, Date, and DateFormat classes should put you in the right direction.

See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

Upvotes: 0

Tushar
Tushar

Reputation: 8049

Use the following code to get a UNIX timestamp:

String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);

Now you have the timestamp, which you know how to use.

Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time

Upvotes: 1

Related Questions