Search code examples
javaxmldomcalendargregorian-calendar

Convert Java Gregorian Calendar to String


I have a Book Class and one of its attributes is:

private Calendar publish_date;

Now I would like to insert a new Book in a library.xml file. So I create a book:

Book b = new Book();
b.setPublish_date(new GregorianCalendar(1975, 5, 7));

I need that date to be a String so that I can write it in XML file (using DOM). So I perform:

    Element publish_date = doc.createElement("publish_date");
    SimpleDateFormat formatter=new SimpleDateFormat("yyyy MM DD"); 
    publish_date.appendChild(doc.createTextNode(formatter.format(b.getPublish_date())));
    book.appendChild(publish_date);

but this is the error:

java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:301)
at java.text.Format.format(Format.java:157)
at fileLock.FileLock.updateLibrary(FileLock.java:127)
at fileLock.FileLock.main(FileLock.java:63)

so which is the correct way to convert a Calendar (Gregorian Calendar) to a string? Thanks


Solution

  • A SimpleDateFormat can't format a GregorianCalendar; it can format a Date, so convert it to a Date first. You are getting 158 as the day, because DD is the day of the year, but dd (lowercase) is the day of month.

    SimpleDateFormat formatter=new SimpleDateFormat("yyyy MM dd");   // lowercase "dd"
    publish_date.appendChild(doc.createTextNode(formatter.format(
        b.getPublish_date().getTime() )));
    

    Also, you may have known, you may not have known, but month numbers are 0-11 in Java, so when formatted, month 5 is June, so it comes out as 06.

    Output:

    1975 06 07