The java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
(or UTC). It means that irrespective of the location in the world, a Date
object represents the same number (milliseconds from the epoch). When you print an object of java.util.Date
, its toString
method returns the date-time in the JVM's timezone, calculated from this milliseconds value. In order to print the date-time in a different timezone, we set the timezone to SimpleDateFormat
and obtain the formatted string from it.
If you do not like the output like Thu Aug 13 23:29:34 EDT 2020
, which is the string returned by Date#toString
in your timezone (and will be different in different timezones), there are two options:
- Represent the
Date
in milliseconds (as described above, it will be the same at any location in the world) obtained using Date#getTime
.
- Keep the original string,
2020-08-14T08:59:34.961+05:30
as it is because it already represents the date-time in the ISO8601 format.
Note that 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*.
A demo of the modern date-time API:
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Date;
public class Main {
public static void main(String args[]) {
String dateFromDatabase = "2020-08-14T08:59:34.961+05:30";
ZonedDateTime zdt = ZonedDateTime.parse(dateFromDatabase);
System.out.println(zdt);
// If at all you need java.util.Date, you can get it from Instant
Instant instant = zdt.toInstant();
Date date = Date.from(instant);
}
}
Output:
2020-08-14T08:59:34.961+05:30
Learn more about the modern date-time API from Trail: Date Time.
* 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.