Search code examples
javacalendarsimpledateformatgregorian-calendar

I have a GregorianCalender in my entity class, how do i create an object which has specific date and display in specific format in toString()?


public class Book {
    Calendar dateOfPublish;

    Book(Calendar dateOfPublish, ...){}

    public Calendar getDateOfPublish() {
        return dateOfPublish;
    }

    public void setDateOfPublish(int day, int month, int year) {
        this.dateOfPublish = dateOfPublish;
    }

    public String toString() {
                return Date Of Publish=" + dateOfPublish.YEAR + "/" + dateOfPublish.MONTH + "/" + 
                       dateOfPublish.DATE;
    }
}

I've tried to instantiate a book object using this this as argument in the Calendar data fielld.

new Book(new GregorianCalendar(2018,3,20));

But when i display the object with toString(), it displays

Results:    
Date Of Publish=1/2/5

I've searched through internet, seeing some people use SimpleDateFormat, but can it be done in an entity class? Or is there any better Date/Calendar class that i should use?


Solution

  • You have declared your method with the completely reverse order of the parameters that you will find in the constructors of any date type available in Java.

    public void setDateOfPublish(int day, int month, int year) {
        //...
    }
    

    The order of parameter in the method declaration should match with the order of arguments you pass to call it and therefore I suggest, you declare your method as follows to avoid accidents:

    public void setDateOfPublish(int year, int month, int day) {
        //...
    }
    

    Also, the java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

    Using the modern date-time API, you can do it as follows:

    import java.time.LocalDate;
    
    class Book {
        LocalDate dateOfPublish;
    
        // ...
    
        public void setDateOfPublish(LocalDate dateOfPublish) {
            this.dateOfPublish = dateOfPublish;
        }
    
        public void setDateOfPublish(int year, int month, int day) {
            this.dateOfPublish = LocalDate.of(year, month, day);
        }
    
        public String toString() {
            return "Date Of Publish=" + dateOfPublish;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Book book1 = new Book();
            book1.setDateOfPublish(LocalDate.of(2018, 3, 20));
            System.out.println(book1);
    
            Book book2 = new Book();
            book2.setDateOfPublish(2020, 2, 10);
            System.out.println(book2);
        }
    }
    

    Output:

    Date Of Publish=2018-03-20
    Date Of Publish=2020-02-10
    

    Learn more about the modern date-time API from Trail: Date Time.