-2

i have a string with "yyyy-MM-dd" date format and i want to pass it to a calender control in java. the way i am doing is giving me a wrong answer Please Help

String da = "1957-01-01"
Date date = Date.parse(da);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

I am getting a output such as Tuesday, April 12, 1952 AD or 3:30:42pm PST[Example]

user3734234
  • 151
  • 1
  • 3
  • 12
  • Your code not even compile. – Ruchira Gayan Ranaweera Aug 06 '14 at 12:05
  • Don't use `Date.parse`, which has been deprecated for *ages*. Use `SimpleDateFormat`. And for *output*, you presumably need to set the format on the control - but we don't have *any clue* what kind of control it is, or even what kind of user interface this is. – Jon Skeet Aug 06 '14 at 12:06
  • possible duplicate of [How to convert a date String to a Date or Calendar object?](http://stackoverflow.com/questions/43802/how-to-convert-a-date-string-to-a-date-or-calendar-object) – blackbishop Aug 06 '14 at 12:11

3 Answers3

3

You can try with SimpleDateFormat

String da = "1957-01-01";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Date date=df.parse(da); // parse your string to date 
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(df.format(calendar.getTime())); // format date
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

You need to give the date a format first:

String da = "1957-01-01"
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(da);
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
Ottertoss
  • 1
  • 2
0

Use SimpleDateformat for this

String strFormat="yyyy/MM/dd"; 
    DateFormat myDateFormat = new SimpleDateFormat(strFormat);
    Date myDate = new Date();
    Calendar calender=new Calender();

    myDate = myDateFormat.parse("2007/05/12");
    myGDate.setTime(myDate);
kirti
  • 4,499
  • 4
  • 31
  • 60