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?
You can parse a string containing a data to date value using the following ways − The constructor SimpleDateFormat class accepts a String value representing the desired date format and creates this object . You can parse the date string using the parse () method of this class.
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. That's untested, but I think it should work.
By default, Java dates are in the ISO-8601 format, so if we have any string which represents a date and time in this format, then we can use the parse () API of these classes directly. Here ‘s a bit more detail on this new API. 2.1. Using the Parse API
The constructor SimpleDateFormat class accepts a String value representing the desired date format and creates this object. You can parse the date string using the parse () method of this class.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With