Skip to content
Advertisement

java.util.Calendar format mm/dd/yyyy and hh:mm:ss

For my java program, I have imported the Calendar class and created a getInstance() called cal. The code below is in its own method and class.

JavaScript

I am trying to add to the String coverage, which will be equal to the code below.

JavaScript

This returns only the current day and hour. How can I make it where it returns the format

Date: mm/dd/yyyy

Time: hh:mm:ss

Advertisement

Answer

java.time

You are using a terrible date-time class that was supplanted years ago by the modern java.time classes defined in JSR 310.

Capture the current moment as seen in a time zone.

JavaScript

Or, specify time zone explicitly.

JavaScript

In Java 15+, we have text blocks feature to make your text creation easier. Text blocks do not support interpolation directly. Use String#format/String#formatted.

JavaScript

When run.

JavaScript

Interoperating with legacy code

If you must use Calendar class to interoperate with old code not yet updated to java.time, you can convert back and forth. Use new conversion methods added to the old classes.

Converting from legacy to modern. Cast to GregorianCalendar. Test with instanceof if any chance of a different concrete class.

JavaScript

Converting from modern to legacy.

JavaScript

If working from a textbook or tutorial using Calendar, you need a more recent textbook or tutorial.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement