Convert String to Calendar

Asked

Viewed 572 times

3

I’m trying to make a conversion of String for Calendar but without success.

My String is in dd/MM/yyyy format. I need to convert to yyyy-MM-dd And set on an object of type Calendar. void setDATAFUNDACAO(java.util.Calendar value);

Here’s my current code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("07/04/2016");
Calendar cal =  sdf.getCalendar();

But unfortunately he launches this exception

Exception in thread "main" java.text.Parseexception: Unparseable date: "07/04/2016" at java.text.Dateformat.parse(Dateformat.java:337) at test.main(test.java:54)

1 answer

4

If you have configured the SimpleDateFormat for "yyyy-MM-dd", this is the format you should use in the command parse:

Date date = sdf.parse("2016-07-04");

That is the reason for exception. The code below worked for me:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("07/04/2016");
Calendar cal =  sdf.getCalendar();

cal.setTime(date);

String df = sdf2.format(date);

System.out.println(cal.getTime());

System.out.println(df);
  • I’ll test it here. In the morning. VLW

Browser other questions tagged

You are not signed in. Login or sign up in order to post.