java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.parse("2020-04-19T01:03:50");
OffsetDateTime odtIndia = ldt.atZone(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
System.out.println(odtIndia);
OffsetDateTime odtUtc = odtIndia.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odtUtc);
}
}
Output:
2020-04-19T01:03:50+05:30
2020-04-18T19:33:50Z
ONLINE DEMO
The Z
in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC
timezone (which has the timezone offset of +00:00
hours).
Learn more about the modern Date-Time API from Trail: Date Time.
Using Joda API:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime ldt = new LocalDateTime("2020-04-19T01:03:50");
DateTime dtIndia = ldt.toDateTime(DateTimeZone.forID("Asia/Kolkata"));
System.out.println(dtIndia);
DateTime dtUtc = dtIndia.toDateTime(DateTimeZone.UTC);
System.out.println(dtUtc);
}
}
Output:
2020-04-19T01:03:50.000+05:30
2020-04-18T19:33:50.000Z
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.