Parsing date from Calendar in Java

27,835

Solution 1

The format is not stored in the Date. It is stored in the String. The Date#toString() returns a fixed format which is described in its Javadoc.

Do the formatting only at the moment you need to display a Date to a human as a String.

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 10);
Date date = calendar.getTime();
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(formattedDate);

Note that MM stands for months and mm for minutes. See also SimpleDateFormat javadoc.

Solution 2

You'll be happy to hear that there's never a need to parse a date from a Calendar object: The way to pull a Date out of a Calendar is via the getTime() method.


EDIT:

To output the date in eDate in ISO style format:

final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String formattedDate = isoFormat.format(eDate.getTime());

That's untested, but I think it should work.

Solution 3

You're inserting a Zulu Timestamp (UNIX), getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. Then you define the format as yyyy-mm-dd hh-mm-ss and try to parse the timestamp with this pattern. Which doesn't match.

You could use Date date = calendar.getTime(); and then format it via new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date);

Solution 4

Don't use toString() for anything like that. toString() should be used only for debug messages.

Use DateFormat.format(..) to produce a string in a predictable form.

Solution 5

You're currently formatting with the default format from java.util.Date, and then parsing with a potentially different format. You should also change your format string - it's currently using a 12 hour clock with no am/pm indicator, and minutes twice. I think you mean: "yyyy-MM-dd HH-mm-ss"

Share:
27,835
Vishal
Author by

Vishal

SDE 2 @Amazon

Updated on April 18, 2020

Comments

  • Vishal
    Vishal about 4 years

    I am having following function

    public static Date parseDate(String date, String format) throws ParseException
     {
             SimpleDateFormat formatter = new SimpleDateFormat(format);
             return formatter.parse(date);
     }
    

    I am using this as follows in my code

    Calendar eDate = Calendar.getInstance();
    eDate.add(Calendar.DAY_OF_MONTH,10);
    Date date = null;
      try {
       date = parseDate(eDate.getTime().toString(),"yyyy-MM-dd hh-mm-ss");
      } catch (ParseException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
    

    But it is throwing -

     java.text.ParseException: Unparseable date
    

    What is the problem here?