ArunDhaJ
ArunDhaJ

Reputation: 631

converting timezone back to local

I'm stuck converting the Date object back to a local timezone. I've googled a lot and couldn't arrive at a solution.

My scenario is: I send a request (with full date string in local timezone 04/01/2014T00:00:00+0530) to a web server which is located in some other timezone than that of mine. The server appropriately converts it to UTC and does some manipulation and sends a CSV file back. I've a date column in CSV which is always in GMT.

String input = "04/01/2014T00:00:00+0530";
DateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ssZ");
DateFormat csvFileDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z");

Date inputDate = inputDateFormat.parse(input); // Mon Mar 31 18:30:00 GMT 2014
// inputDateFormat.getTimeZone(); // is always GMT

// After some processing I create CSV file
// within a loop
Date csvDate = // got Date from some operation, for simplicity I removed the code.
csvFileDateFormat.format(csvDate); // **HERE IS THE ISSUE**
// end of loop

I wanted to set the timezone of csvFileDateFormat correctly. Below code works, but I don't want to hard code "GMT+05:30". Instead need to extract the timezone only from input string.

csvFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); // I dont want to hard code

Any help is highly appreciated. PS: I don't have option to use any other libraries, like joda, etc...

Regards ArunDhaJ

Upvotes: 0

Views: 170

Answers (2)

Remi878
Remi878

Reputation: 341

Maybe this function will help you :

private static TimeZone getTimeZoneFromString(String inputDateStr)
{
    // TimeZone inputTimeZone = null;
    // null or default
    TimeZone inputTimeZone = TimeZone.getDefault();
    try
    {
        DateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ssZ");
        Date inputDate = inputDateFormat.parse(inputDateStr);
        Date inputDate2 = inputDateFormat.parse(inputDateStr.substring(0, 19) + "+0000");
        int offset = (int) (inputDate2.getTime() - inputDate.getTime());
        for (String tzId : TimeZone.getAvailableIDs())
        {
            TimeZone tz = TimeZone.getTimeZone(tzId);
            if (tz.getOffset(inputDate.getTime()) == offset)
            { // take the first matching one, display name doesn't matter
                inputTimeZone = tz;
                break;
            }
        }
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }
    return inputTimeZone;
}

Upvotes: 1

Fallso
Fallso

Reputation: 1301

You could use Locale.getDefault() to return the default timezone for the system it is being run on. If you don't want to return that, then it should be safe to hard code it.

Upvotes: 0

Related Questions