-2

I'm trying to convert an UTC date/time String to another timezone. It just shows the date/time in UTC timezone.

Code below:

        apiDate = "2013-04-16T16:05:50Z";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
        Date date = dateFormat.parse(apiDate);

        Calendar calendar = Calendar.getInstance();
        TimeZone timeZone = calendar.getTimeZone();

        SimpleDateFormat newDateFormat = new SimpleDateFormat("hh:mm aa, MMMM dd, yyyy");
        newDateFormat.setTimeZone(timeZone);
        String newDateString = newDateFormat.format(date);
Bogdan Zurac
  • 6,348
  • 11
  • 48
  • 96
  • possible duplicate of [Converting UTC dates to other timezones](http://stackoverflow.com/questions/6088778/converting-utc-dates-to-other-timezones) – Brian Roach Apr 15 '13 at 14:07
  • Yes, it actually is a duplicate. Sorry, but I did spent quite some time searching for an answer, but I didn't stumble upon that thread. Thanks anyway ! – Bogdan Zurac Apr 15 '13 at 14:13
  • It automatically popped up when you typed in your question's subject, which is why it was also the top link on the right side of this screen. – Brian Roach Apr 15 '13 at 14:34

2 Answers2

2

You should set your "parsing" SimpleDateFormat into UTC. Otherwise it will actually be assuming your default time zone at parse time:

TimeZone utc = TimeZone.getTimeZone("Etc/UTC");
dateFormat.setTimeZone(utc);

You also don't need to construct a calendar to get the system-default time zone - just use:

TimeZone defaultZone = TimeZone.getDefault();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;

public class Test {

    public static final SimpleDateFormat fDateTime = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss");

    public static void main(String[] args) {

        String output = getFormattedDate("2016-03-1611T23:27:58+05:30");
        System.out.println(output);

    }

    public static String getFormattedDate(String inputDate) {

        try {
            Date dateAfterParsing = fDateTime.parse(inputDate);

            fDateTime.setTimeZone(TimeZone.getTimeZone("timeZone"));

            return fDateTime.format(dateAfterParsing);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
Ankit Jain
  • 2,230
  • 1
  • 18
  • 25