-1

I'm getting a long printout of my GregorianCalendar when I only want to print the Year, Month, and Day.

This is what I get:

dateOfBirth=java.util.GregorianCalendar[time=173592000000,areFieldsSet=true,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=1975,MONTH=6,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=3,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]}Faculty{dateOfHire=java.util.GregorianCalendar[time=173592000000,areFieldsSet=true,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=1975,MONTH=6,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=3,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?], dateOfTermination=java.util.GregorianCalendar[time=173592000000,areFieldsSet=true,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=1975,MONTH=6,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=3,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]

**Person Class with the dateOfBirth field* package hierarchybaseclasses;

import hierarchyinterfaces.IPerson;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Person implements IPerson {

    private String name;
    private String address;
    private String socialSecurityNumber;
    private GregorianCalendar dateOfBirth;

    public Person(){
        this.name = "";
        this.address = "";
        this.socialSecurityNumber = "";
        this.dateOfBirth = new GregorianCalendar();
    }
     public Person(String name, String address, String socialSecurityNumber, 
GregorianCalendar dateOfBirth) {
        this.name = name;
        this.address = address;
        this.socialSecurityNumber = socialSecurityNumber;
        this.dateOfBirth = new GregorianCalendar();
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
         return address;
    }

    public void setAddress(String address) {
         this.address = address;
    }

    public String getSocialSecurityNumber() {
        return socialSecurityNumber;
    }

    public void setSocialSecurityNumber(String socialSecurityNumber) {
        this.socialSecurityNumber = socialSecurityNumber;
    }

    @Override
    public GregorianCalendar getDateOfBirth() {
        Date date = new Date();
        dateOfBirth.setTime(date);
       // dateOfBirth.getTime();
        return dateOfBirth;
     }


     public void setDateOfBirth(GregorianCalendar dateOfBirth) {
        //Date date = new Date();
        //dateOfBirth.setTime(date);
        dateOfBirth.getTime();
        this.dateOfBirth = dateOfBirth;

    }



    @Override
    public String toString() {
        return "Person{" + "name=" + name + ", address=" + address + ", 
socialSecurityNumber=" + socialSecurityNumber + ", dateOfBirth=" + 
dateOfBirth + '}';
    }


}

Test Class This is what the instructor provided.

package hierarchybaseclasses;

import java.util.GregorianCalendar;

public class TestClassAssignment3 {   

    public static void main(String[] args) {

        // Create a date which will be used in all test methods
        GregorianCalendar testDate = new GregorianCalendar(1975, 
GregorianCalendar.JULY, 3);

        // Create a classroom 
        Classroom classroom = new Classroom("PA100", "LECTUREHALL");
        System.out.println(classroom.toString());

        // Create a Faculty member
        // Uses the date created above
        Faculty faculty = new Faculty();
        faculty.setDateOfBirth(testDate);
        faculty.setName("Elizabeth Kramer");
        faculty.setAddress("1 University Ave");
        faculty.setSocialSecurityNumber("123456789");
        faculty.setStatus("PARTTIME");
        faculty.setDateOfHire(testDate);
        faculty.setDateOfTermination(testDate);
        faculty.setSalary(10000000);

        // Create an Offered Course 
        // Uses the classroom created above
        OfferedCourse newCourseOffering = new OfferedCourse("INFO301", "Java 
Programming", classroom);
        System.out.println(newCourseOffering.toString());

        // Create a FacultyCourse (link to course id of newCourseOffereing 
created above)
        FacultyCourse facultyCourse = new 
FacultyCourse(newCourseOffering.getCourseId());

        // Add to list of courses for the faculty
    faculty.getListOfCourses().add(facultyCourse);
        System.out.println(faculty.toString());

       // Create a Student 
        Student newStudent = new Student();
        newStudent.setDateOfBirth(testDate);
        newStudent.setName("Kathy Smith");
        newStudent.setAddress("1 Beech Ave");
        newStudent.setSocialSecurityNumber("567876567");
        newStudent.setDateOfGraduation(testDate);
        newStudent.setCurrentGPA(0.0f);

        // Create a Student Course (link to course id of newCourseOffereing 
created above)
        StudentCourse studentCourse = new 
StudentCourse(newCourseOffering.getCourseId());

        // Add course to student's list of courses
        newStudent.getEnrolledCourses().add(studentCourse);

        // Add grades to Student's Course 
        studentCourse.getCourseGrades().add(90.5f);
        studentCourse.getCourseGrades().add(100.0f);
        studentCourse.getCourseGrades().add(70.5f);
        studentCourse.getCourseGrades().add(65.0f);
        System.out.println(newStudent.toString());

    }
 }
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ryan Evans
  • 1
  • 1
  • 2
  • 1
    I tried to format that top bit, but it's just a disaster. I'm not sure what you're going for there. – Carcigenicate Feb 12 '18 at 15:43
  • 1
    I'm not sure this comes anywhere close to a minimal example. – Mad Physicist Feb 12 '18 at 16:30
  • `GregorianCalendar` is long outdated and poorly designed. The good answer is to use `LocalDate` from [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). The modern API is so much nicer to work with. And `LocalDate` is simpler, more natural, clearer and cleaner and matches your requirements exactly. And you won’t need anyting like the conversion between `Date` and `GregorianCalendar`. – Ole V.V. Feb 12 '18 at 20:05

4 Answers4

2

Look at java.text.DateFormat and java.text.SimpleDateFormat (keep in mind: instances are not threadsafe and therefore you should have local, use-once instances instead of creating static ones).

Better yet, be done with java.util for date/time and switch to java.time (your dob would be a LocalDate then)

giorgiga
  • 1,758
  • 12
  • 29
1

What you are looking for is not the date itself, but a short text representation of it. For that, you have to use a formatter, for example:

dateOfBirth.toZonedDateTime().format(DateTimeFormatter.ISO_DATE)

Piotr Wilkin
  • 3,446
  • 10
  • 18
curlyBraces
  • 1,095
  • 8
  • 12
0

tl;dr

myGregCal               // Avoid troublesome legacy class.
    .toZonedDateTime()  // Convert from legacy class to modern.
    .toLocalDate()      // Extract a date-only object without time-of-day and without time zone. 
    .toString()         // Generate a String in standard ISO 8601 format. 

1975-07-03

Avoid legacy classes

The troublesome GregorianCalendar class is now legacy, supplanted by the java.time classes.

ZonedDateTime

Convert from the legacy classes to the modern by calling new methods added to the old classes.

ZonedDateTime zdt = myGregCal.toZonedDateTime() ;

LocalDate

If you want only the date without a time-of-day and without a time zone, extract a LocalDate.

LocalDate ld = zdt.toLocalDate() ;

Generate strings

Generate a String in standard ISO 8601 format by default without need of a formatting pattern.

String output = ld.toString() ;

Generate a string localized automatically. Specify a Locale to determine the human language and cultural norms used in localizing.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f ) ;

Redefine your member variable

Your class should be redefined to use LocalDate as the type of the member variable. If you goal is to represent a date-only value, then do not use a date-with-time type. And, as mentioned above, the GregorianCalendar class is notoriously troublesome and poorly designed, replaced years ago in Java 8 and Java 9 by the java.time classes defined in JSR 310.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-1

Since you apparently don’t have experience with DateFormats or DateTimeFormatters, I’m going to suggest a much simpler approach:

String date = 
    dateOfBirth.get(Calendar.YEAR) +
    "-" +
    (dateOfBirth.get(Calendar.MONTH) + 1) +
    "-" +
    dateOfBirth.get(Calendar.DAY_OF_MONTH);

The reason for adding 1 to the month value is that get(Calendar.MONTH) does not return a month number. It returns a Calendar month constant, like Calendar.JANUARY, Calendar.FEBRUARY, …, and those constants’ numeric values are 0, 1, 2, ….

You can also use an implicit Formatter:

String date = String.format("%tF", dateOfBirth);
VGR
  • 40,506
  • 4
  • 48
  • 63