sp00m
sp00m

Reputation: 48817

Make java.text.DateFormat parse to java.util.Calendar

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

Upvotes: 2

Views: 2951

Answers (3)

Mohamed AbdElRazek
Mohamed AbdElRazek

Reputation: 1684

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());

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

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

Upvotes: 3

partlov
partlov

Reputation: 14277

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.

Upvotes: 2

Related Questions