I am trying to do it without methods so that I can better grasp the concept.
I am really close. My hours math seems to be off. What am I not understanding there?
static void showCurrent(){
Date today = new Date();
long milliseconds = today.getTime(); // ex: 1651773923837
long seconds = milliseconds / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long s = seconds % 60;
long m = minutes % 60;
long h = hours % 24;
System.out.printf("Date: %s, Time: %d\n", today.toString(), milliseconds);
System.out.println(h + ": " + m + ": " + s );
Output:
Date: Fri May 06 10:13:21 EDT 2022, Time: 1651846401839
14: 13: 21
The LocalDateTime.now() method returns the instance of LocalDateTime class so if you print the instance of LocalDateTime class, it will print the current time and time. To get it the the right format you need to format the current date using DateTimeFormatter class included in JDK 1.8
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class CurrentDateTime {
public static void main(String[] args) {
DateTimeFormatter date_wanted = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(date_wanted.format(now));
}
}