Conversion from UTC to IST returning same value in JAVA using Joda time library

I need to convert TimeZone in my project from UTC to IST and vice versa. For that purpose I am using Joda time jar in my project. But the problem occurs when I try to convert the string from UTC to IST, I am getting the same value instead of getting converted IST value. Kindly please mentor me in which part of code I am completely stuck up. My code is as follows:

public class JodaDemo {

    public static final String DATE_PATTERN_SERVICE = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_PATTERN_SERVICE_NO_SECONDS = "yyyy-MM-dd HH:mm";

    public static void main(String[] args) {

        getDateFromUTCtoIST("2015-08-23 10:34:40");

    }
private static void getDateFromUTCtoIST(String dateTime) {

        DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_PATTERN_SERVICE);
        DateTime jodatime = dtf.parseDateTime(dateTime);
        DateTimeZone indianTimeZone = DateTimeZone.forID("Asia/Kolkata");
        DateTime indianTime = jodatime.withZone(indianTimeZone);

        System.out.println(indianTime);

    }

OUTPUT:

2015-08-23T10:34:40.000+05:30

Expected output:

Converted TimeZone (+5:30 output) like in yyyy-MM-dd HH:mm:ss format

Jon Skeet
people
quotationmark

There are two problems here. Firstly, when you're parsing the value you're not specifying the time zone - so it's using your local time zone. Secondly, you're not using any formatter for the result - you're just calling DateTime.toString(), implicitly.

The simplest approach is actually to create two formatters for the same pattern, one in UTC and one in the relevant time zone - then you don't need to manually convert at all, as the formatter can do it for you:

import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;

public class Test {

  public static final String DATE_PATTERN_SERVICE = "yyyy-MM-dd HH:mm:ss";

    public static void main(String[] args) {        
        DateTimeFormatter utcFormatter = DateTimeFormat
            .forPattern(DATE_PATTERN_SERVICE)
            .withLocale(Locale.US)
            .withZoneUTC();
        DateTimeZone indianZone = DateTimeZone.forID("Asia/Kolkata");
        DateTimeFormatter indianZoneFormatter = utcFormatter.withZone(indianZone);

        String utcText = "2015-08-23 10:34:40";
        DateTime parsed = utcFormatter.parseDateTime(utcText);
        String indianText = indianZoneFormatter.print(parsed);
        System.out.println(indianText); // 2015-08-23 16:04:40
    }
}

people

See more on this question at Stackoverflow