Should we use the Date Object in java?
Should we use de java.util.Date object in java? It has so many Deprecated methods that is a little anoying to have to use a complex method to something that should be so simples.
I am using something stupid to emulate getDate() like:
public static int toDayMonth (Date dt)
{
DateFormat df = new SimpleDateFormat("dd");
String day = d开发者_运维百科f.format(dt);
return Integer.parseInt(day);
}
It has to be better way...
Might be a matter of preference, but I use Joda Time.
Looking at the DateTime
API from Joda Time,
DateTime#dayOfMonth
might be what you were looking for.
DateTime dt = new DateTime();
// no args in constructor returns current date and time
DateTime.Property day = dt.dayOfMonth();
System.out.println(day.get()); // prints '27'
The Java Date class is notorious for being confusing and clunky. I'd recommend looking at the popular "Joda Time" library:
http://joda-time.sourceforge.net/
No, you shouldn't really use java.util.Date anymore.
GregorianCalendar is an alternative that you can use:
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.MONTH, Calendar.JUNE);
cal.set(Calendar.DAY_OF_MONTH, 27);
cal.set(Calendar.YEAR, 2010);
The javadoc for each method says what it's been replaced by. To emulate getDate()
, use:
Calendar.get(Calendar.DAY_OF_MONTH)
EDIT: Full example:
public static int toDayMonth (Date dt) {
Calendar c = new GregorianCalendar();
c.setTime(dt);
return c.get(Calendar.DAY_OF_MONTH);
}
精彩评论