Search code examples
androidsimpledateformatandroid-date

Date Formatting using only date and month?


I need to construct a date which will display only day and month example:- 23 Dec . I have day value and month value only but how do I use SimpleDateFormat to construct a formatted date with format like "dd-MMM".How do I modified the below method to return the formatted date?

public String formatDate(String day, String month, String year) {
        // Do something with the date chosen by the user
        SimpleDateFormat df = new SimpleDateFormat("dd-MMM");
    }

Suppose if I call above method like formatDate("11","1","") then it should return me "11 Jan".


Solution

  • This should work:

    The year value is set to 0 since you do not have it but you can pass that in to the set method.

    public String formatDate(String day, String month, String year) {
      // Do something with the date chosen by the user
      SimpleDateFormat df = new SimpleDateFormat("dd-MMM");
    
      Calendar c = Calendar.getInstance();
      c.set(0, Integer.parseInt(month)-1, Integer.parseInt(day));
      return df.format(c.getTimeInMillis());
    

    }