1

I am having string date = "2014-09-11".

i want to set this string to calendar object.

The string value is already having "-" in it. So how to use date formatting?

pratz9999
  • 539
  • 4
  • 20
  • possible duplicate of [How to parse date string to Date?](http://stackoverflow.com/questions/4496359/how-to-parse-date-string-to-date) – Blacklight Dec 04 '14 at 13:05
  • possible duplicate of [Convert String to Calendar Object in Java](http://stackoverflow.com/questions/5301226/convert-string-to-calendar-object-in-java) – Rangad Dec 04 '14 at 13:06
  • yes it worked! It was a confusing because of parsing. – pratz9999 Dec 04 '14 at 13:18

3 Answers3

6

You should use a date format to parse your string

String dateStr = "2014-09-11";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
DateTime date = format.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Xavier Falempin
  • 1,186
  • 7
  • 19
0

try this code:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateInString = "2014-09-11";

try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

} catch (ParseException e) {
    e.printStackTrace();
}
Prashant Jajal
  • 3,469
  • 5
  • 24
  • 38
0

try this

    String date = "2014-09-11";
    String dt[]=date.split("-");
    Calendar cal=Calendar.getInstance();
    cal.add(Calendar.DATE, Integer.parseInt(dt[2]));
    cal.add(Calendar.MONTH,Integer.parseInt(dt[1]));
    cal.add(Calendar.YEAR,Integer.parseInt(dt[0]));

    System.out.print(cal.getTime().toString());
Ravi
  • 34,851
  • 21
  • 122
  • 183
  • It should be cal.set(), now you are adding to current calendar. Also, Calendar.MONTH is from 0-11 so there should be -1 (when using set) there as well. – Carnal Dec 04 '14 at 14:09