Ronaldinho Learn Coding
Ronaldinho Learn Coding

Reputation: 13824

Date Format Java?

I have 3 int variables for Month, Day and Year.

How can I convert them to a java.util.Date object (or whatever).

For Example, Month = 12, Date = 20, Year = 2011

It should be print in medium date format: **Dec 20, 2011**

Thank you very much!

Edit here my try:

String yourBirthDay = Integer.toString(birthMonth) + "." + Integer.toString(birthDay) + "." + Integer.toString(birthYear);
        DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);

        try {
            Date date = format.parse(yourBirthDay);
            System.out.println("Your birth date is : " + date.toString());

        } catch (ParseException pe) {
            System.out.println("ERROR: could not parse date in string \""
                    + yourBirthDay + "\"");
        }

Upvotes: 0

Views: 660

Answers (1)

ElderMael
ElderMael

Reputation: 7101

I did this little test using Calendar.set(int year,int month, int date):

@Test
public void testDate() throws ParseException {

    int year = 2011, month = 12, date = 20;

    Calendar calendar = Calendar.getInstance();

    calendar.set(year, month - 1, date);

    Date javaDate = calendar.getTime();

    // SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");

    DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM);

    String stringDate = format.format(javaDate);

    assertEquals("Dec 20, 2011", stringDate);

}

You need to remove 1 from the month because java.util.Calendar works with zero based months.

Upvotes: 6

Related Questions