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.

import java.util.Calendar;
Calendar cal = Calendar.getInstance();

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

coverage = String.format("%nPAYOUT FOR EARTHQUAKE DAMAGE"
                           + "%n%SHomeowner:  " + insured
                           + "%nDate:  " + cal.get(Calendar.DATE)
                           + "%nTime:  " + cal.get(Calendar.HOUR));

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.

ZonedDateTime zdt = ZonedDateTime.now() ;  // Uses JVM’s current default time zone.

Or, specify time zone explicitly.

ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

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.

String insured = "Bob";
String template =
        """
        PAYOUT FOR EARTHQUAKE DAMAGE
        Homeowner: %1$s
        Date: %2$s
        Time: %3$s
        """;
String coverage =
        template.formatted(
                insured ,
                zdt.format(
                        DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US )
                ) ,
                zdt.format(
                        DateTimeFormatter.ofLocalizedTime( FormatStyle.MEDIUM ).withLocale( Locale.US )
                )
        );

System.out.println( "coverage = " + "n" + coverage );

When run.

coverage = 
PAYOUT FOR EARTHQUAKE DAMAGE
Homeowner: Bob
Date: Feb 27, 2022
Time: 3:20:32 PM

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.

ZonedDateTime zdt = ( ( GregorianCalendar ) calendar ).toZonedDateTime() ;

Converting from modern to legacy.

Calendar cal = GregorianCalendar.from( zdt ) ;

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