Question

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...

Was it helpful?

Solution

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

OTHER TIPS

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.

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top