0

In my android application I have to parse a date of format EEE, dd MMM yyyy HH:mm:ss zzz. I am extracting the time from this using below method. this works perfect. but the time always displays in GMT format, so I have to convert it in to user time zone, for that I have added one more line in my code before parsing, the code is inputFormatter.setTimeZone(TimeZone.getDefault()); since this is not working I have changed the argument in to TimeZone.getTimeZone("UTC"), TimeZone.getTimeZone("Asia/Kolkata") and so on, but nothing works, the time still comes in GMT format.

what is the problem for this actually ? how can I resolve this, any help is appreciated

public static String extractTime(String dateInput) {
        Date date = null;
        String time;

        try {
            DateFormat inputFormatter = new SimpleDateFormat(mFormat, Locale.getDefault());
            date = inputFormatter.parse(dateInput);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat outputFormatter = new SimpleDateFormat("HH:mm:ss");
        time = outputFormatter.format(date);
        return time;
    }

Update

I have tried setting timezone to outputFormatter instead of inputFormatter, but it is still same, no change in output.

Example :

Input : Tue, 21 Jul 2015 09:02:30 GMT

Output getting : 05:02:30

droidev
  • 7,352
  • 11
  • 62
  • 94

1 Answers1

1

A couple of things to note about dates and DateFormat. A date object in Java is always in UTC - the way how it is printed (even in things like System.out.println()) depends on the timeZone (e.g. in sysout the timeZone is the system's default TZ).

So, having said that let's come to your problem. You first want to parse a String that contains a date in a certain timeZone. Let's assume that datestring is in the user's TZ - to convert it to the correct UTC time you have to tell the DateFormat which TZ the String is in that it is parsing:

// Assuming you have the userTimeZone already
inputFormatter.setTimeZone(userTimeZone);

When you now parse the date you get the correct java.util.Date object. If you want to format this to get a String that only contains the hours, minutes and seconds you again have to define the desired target TZ. Assuming this is also the user's TZ:

outputFormatter.setTimeZone(userTimeZone);

When you now format the date with this formatter you will get the time String in the user's TZ.

nutfox
  • 484
  • 3
  • 13