2012-11-21 4 views
0

J'ai 3 variables int pour le mois, le jour et l'année. Comment puis-je les convertir en objet java.util.Date (ou autre).Format de date Java?

Par exemple, Mois = 12, date = 20, Année 2011 =

Il faut imprimer en format de date moyenne: **Dec 20, 2011**

Merci beaucoup!

Modifier ici mon essai:

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 + "\""); 
     } 

Répondre

6

Je l'ai fait petit test en utilisant 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); 

} 

Vous devez supprimer 1 du mois parce que java.util.Calendar travaille avec zéro mois sur la base .

+0

Pouvez-vous le modifier en utilisant seulement DateFormat (pas SimpleDateFormat) ??? –

+2

'DateFormat.getDateInstance (DateFormat.SHORT)' retournera '12/20/11' au lieu de' Dec 20, 2011', est-ce correct? – ElderMael

+1

Édité, il suffit d'utiliser 'DateFormat.MEDIUM' – ElderMael