Changing the format of a complex date in Java

I am trying to return a validity date, or an expiration date for a file, if you will. Currently, I have a sample program that prints out all the needed information but nnot exactly in the format I get. My code prints out:

Thu May 15 04:57:36 PDT 2014

But I need it to print out like so:

Thu, 15 May 2013 04:57:36 PDT

As you can see, very similar just not quite in the right place. Here is my test code that gives me the first result:

    import java.util.Calendar;
    import java.util.Date;

    public class TestCalendar{
       public static void main(String[] args){
          Calendar currentDate = Calendar.getInstance();
          currentDate.setTime(new Date());
          currentDate.add(Calendar.MINUTE, 24);
          Date newDate = currentDate.getTime();

          System.out.println("Date: " + newDate);
       }
    }

This code adds 24 minutes to the current time and then prints it out, I just cant figure out how to reformat this date. SimpleDateFormat doesn’t seem like it’s going to work but I could be wrong. I just couldn’t figure it out.

Thanks in advance for any help anyone is able to give me!!

Answer

Use SimpleDateFormat:

DateFormat formatter= new SimpleDateFormat("E, d MMM yyyy hh:mm:ss zzz");
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(new Date());
currentDate.add(Calendar.MINUTE, 24);
Date newDate = currentDate.getTime();
System.out.println(formatter.format(newDate));

Leave a Reply

Your email address will not be published. Required fields are marked *