How to get the current date/time in Java
To get the current date and time in Java, you can use the java.time
package introduced in Java 8.
Here is an example of how to get the current date and time using the LocalDateTime
class:
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current Date and Time: " + currentTime);
}
}
This will print the current date and time in the format "yyyy-MM-ddTHH:mm:ss.nnnnnnnnn", where T
is the separator between the date and time parts, and nnnnnnnnn
represents the fraction of the second.
For example, the output might look like this: "2022-12-31T12:34:56.123456789"
If you just want the current date, you can use the LocalDate
class instead:
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
System.out.println("Current Date: " + currentDate);
}
}
This will print the current date in the format "yyyy-MM-dd".
If you want to get the current time only, you can use the LocalTime
class:
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime currentTime = LocalTime.now();
System.out.println("Current Time: " + currentTime);
}
}
This will print the current time in the format "HH:mm:ss.nnnnnnnnn", where nnnnnnnnn
represents the fraction of the second.
You can also use the ZonedDateTime
class to get the current date and time in a specific time zone. For example:
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println("Current Date and Time in Tokyo: " + currentTime);
}
}
This will print the current date and time in the format "yyyy-MM-ddTHH:mm:ss.nnnnnnnnn[Asia/Tokyo]", where T
is the separator between the date and time parts, nnnnnnnnn
represents the fraction of the second, and [Asia/Tokyo]
indicates the time zone.