javaandroiddate-parsing

Date from two strings on android


I have two strings for a date (using the current year):

  1. a day = "15"
  2. a month = "7"

With this data I would like to have a string date with this format: Tuesday July 15

Is that possible?

I´m trying with this code but it doesn't work:

 public void dateFormatMoth(String day, String month){

 Date date = null;

    String newDateStr="";
    String dateReceived="day/month";

    SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM");
    SimpleDateFormat myFormat = new SimpleDateFormat("EEEE-MM-dd");

    try {

         reformattedStr = myFormat.format(fromUser.parse(dateReceived));
    } catch (ParseException e) {
        e.printStackTrace();
    }

   Log.d(LOG_TAG,"day formatted"+newDateStr);
}

Solution

  • Just change your myFormat slightly to achieve this. MM will give you month as number, MMMM will give you the full name:

    public void dateFormatMonth(String day, String month) throws ParseException {
        SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM");
        SimpleDateFormat myFormat = new SimpleDateFormat("EEEE MMMM dd", Locale.US);
        try {
            reformattedStr = myFormat.format(fromUser.parse(day + "/" + month));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.d(LOG_TAG,"day formatted"+newDateStr);
    }
    

    You can read more about the different formats in the JavaDoc.

    Note that I specified the locale explicitly, to make sure you got the output you requested regardless of the locale of your machine.