The most voted answer (i.e. the epoch milliseconds for any date ranging from 2001-09-09T01:46:40 UTC to 2286-11-20T17:46:39.999 UTC will have 13-digits) is spot-on. This is a supplement to that answer for anyone interested to know how one may arrive at those figures.
Usually, I write the solution using the modern date-time API first but in this case, I will reverse the pattern because java.time
, the modern date-time API was released in Mar-2014 (2 years after the most voted answer was posted.
Using the legacy date-time API:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println(sdf.format(new Date(1000000000000L))); // 2001-09-09T01:46:40.000Z
System.out.println(sdf.format(new Date(9999999999999L))); // 2286-11-20T17:46:39.999Z
}
}
Using java.time
, the modern date-time API:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
System.out.println(Instant.ofEpochMilli(1000000000000L)); // 2001-09-09T01:46:40Z
System.out.println(Instant.ofEpochMilli(9999999999999L)); // 2286-11-20T17:46:39.999Z
}
}
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 java.time
, 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.
System.currentTimeMillis()
returns a Javalong
. It will always be exactly 64 bits long and will typically have a number of leading zeroes. – Kurtzig