java.util.Date and java.util.Calendar

  1. Getting last day of a month:
    //The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0;
    int month = 1; //So 1 wil l be FEBRUARY
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
    java.util.Date maxDateInMonth = c.getTime();

  2. Formatting date as String:
    java.util.Date myDate = new java.util.Date();
    java.text.SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    //For others patterns click here
    String formattedDate = null;
    try {
    formattedDate = sdf.format(myDate);
    } catch (Exception e) {
    e.printStackTrace();
    }


  3. Change String format of a date:
    String strDate = "2008-10-11";
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
    String converted = null;
    try {
    converted = sdf2.format( sdf1.parse(date) );
    // converted will be "10/11/2008"
    } catch (Exception e) {
    e.printStackTrace();
    }

0 commenti: