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: If you want to get just date and time (and not the timezone information), you can use LocalDateTime.#now(ZoneId)
.
The non-parametrized overloaded, LocalDateTime.#now
returns the current Date-Time using the JVM's timezone. It is equivalent to using LocalDateTime.now(ZoneId.systemDefault())
.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now(ZoneId.of("Europe/Madrid"));
System.out.println(now);
}
}
Output from a sample run:
2021-07-25T15:54:31.574424
ONLINE DEMO
If you want to get the date and time along with the timezone information, you can use ZonedDateTime.#now(ZoneId)
. It's non-parametrized variant behave in the same manner as described above.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Madrid"));
System.out.println(now);
}
}
Output from a sample run:
2021-07-25T16:08:54.741773+02:00[Europe/Madrid]
ONLINE DEMO
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.