Use java.time, the modern Java date and time API, for your date and time work, and it all goes simpler and less error-prone than with the old-fashioned classes. DateFormat
, SimpleDateFormat
, Date
and Calendar
were troublesome and were obsoleted by java.time in Java 8 more than 10 years ago, a couple of months before you asked this question.
Use this formatter:
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss", Locale.ROOT);
Do like this:
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
System.out.println("Now: " + now.format(formatter));
ZonedDateTime in10Hours = now.plusHours(10);
System.out.println("In 10 hours: " + in10Hours.format(formatter));
Get output like:
Now: 02/17/2025 20:19:47 In 10 hours: 02/18/2025 06:19:47
Oracle Tutorial: Trail: Date Time explaining how to use java.time