But how do I get long value(time stamp) of local time ??
A local date-time in a timezone is just a representation of the universal instant in that timezone. The new java.util.Date()
gives us that universal instant i.e. it simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString
function applies the JVM's timezone to return a String
in the format, EEE MMM dd HH:mm:ss zzz yyyy
, derived from this milliseconds value. In other words, the same milliseconds will be represented as different date-times in different timezones. The vice versa: at any given moment, date-times in different timezones will give us the same number of epoch milliseconds.
java.time
The object corresponding to new java.util.Date()
in java.time
, the modern Date-Time API is Instant.now()
.
A demo of java.time
, the modern Date-Time API:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Let's assume 2021-06-26T23:35:50 is the local date-time in India
LocalDateTime ldtIndia = LocalDateTime.parse("2021-06-26T23:35:50");
Instant instant = ldtIndia.atZone(ZoneId.of("Asia/Kolkata")).toInstant();
long millis = instant.toEpochMilli();
System.out.println(millis);
}
}
Output:
1624730750000
ONLINE DEMO
You can convert Instant
and java.util.Date
to each other using
java.util.Date#from(Instant)
and java.util.Date#toInstant()
.
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.