79446413

Date: 2025-02-17 19:25:41
Score: 0.5
Natty:
Report link

Modern answer: java.time

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

Tutorial link

Oracle Tutorial: Trail: Date Time explaining how to use java.time

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Halim Mammadov