2

Usually, I was doing it like this:

DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date d = f.parse("2012-12-21");
Calendar c = Calendar.getInstance();
c.setTime(d);
bean.setDate(c);

But I just found that working solution:

DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
f.parse("2012-12-21");
bean.setDate(f.getCalendar());

Why nowhere in the doc, it is specified that parse() (for exemple) keeps in mind the value after parsing instead of simply returning it? Is it a bad way to do? I feel like having been betrayed all these years long...

sp00m
  • 47,968
  • 31
  • 142
  • 252
  • 2
    It might work, but the API states that parse returns the parsed Date. I would rather depend on a public specified API than an implementation detail that might change. – NilsH Mar 20 '13 at 11:21

3 Answers3

3

Calendar is mutable, if you parse a new date with the same SimpeDateFormat instance your bean's date / calendar may change

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

I think it is bad. DateFormat has Calendar instance which is used to set date during parsing. This instance can be set with setCalendar method, if you want to do instance for another locale for example. After parsing date this instance simply stay in previous state and that is in current implementation, in future this value maybe cleared after parse method returns so I would not rely on this implementation. getCalendar() is in fact used so you can see what is current "kind" of Callendar in use, which locale and so on, but not for getting current value.

partlov
  • 13,789
  • 6
  • 63
  • 82
0

i think you needn't to create instance from Calendar and use dateFormat directly:

DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
f.format(f.parse("2012-12-21"));
bean.setDate(f.getCalendar());
Mohamed AbdElRazek
  • 1,654
  • 14
  • 17