Question

Below, I've got a chunk of code that returns a date in the format of "Sat May 02 00:00:00 MST 1970" (assuming it receives an input of 05/02). How do I format this so that I've just got "May 02"? It doesn't matter to me if I format it here in this block of code or in my print statement.

My current print statement is System.out.print(Date.getAlphabetDate().

public static Date getAlphabetDate()
{
    try
    {
        String tempDate = month + "/" + day;
        Date alphabetDate = new SimpleDateFormat("M/d").parse(tempDate);
        return alphabetDate;
    }
    catch(Exception e)
    {
        return null;
    }
}
Was it helpful?

Solution

You are misunderstanding what SDF does. It returns a Date object, not the String representation of that object. And while a Date object has all that baggage that you're not interested in, you shouldn't care too much about it, since to get a similar String representation of the Date returned, simply use the same or a similar SDF object and use it to format the date:

String stringRep = mySDF.format(myDate);

As an aside, note that whenever code is written with a catch block that returns null, a puppy dies somewhere.


Edit
For example,

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SdfFun {
   private static final String PATTERN = "MM/dd";
   private static final SimpleDateFormat SDF = new SimpleDateFormat(PATTERN);

   public static Date getAlphaDate(int month, int day) throws ParseException {
      String tempDate = month + "/" + day;
      return SDF.parse(tempDate);
   }

   public static void main(String[] args) {
      Date date = null;
      try {
         date = getAlphaDate(2, 16);

         System.out.println(SDF.format(date));
      } catch (ParseException e) {
         e.printStackTrace();
      }
   }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top