tags:

views:

110

answers:

4

Hi.

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 = df.format(dt);
    return Integer.parseInt(day);
}

It has to be better way...

+5  A: 

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'
Anthony Forloney
I think this is a good idea, as last I heard Joda Time was being considered for inclusion in Java 7. I may be mistaken though
Phil
@Phil: I have read somewhere that they weren't going to port over Joda Time into Java 7, but to try to learn from it.
Anthony Forloney
+3  A: 

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/

Andy White
+2  A: 

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);
}
Michael Mrozek
Yes, I have seen that line "Calendar.get(Calendar.DAY_OF_MONTH)".But how to use it? Where do i put the date object?
Jose Conde
you have to set the date of the Calendar object. calendar.setDate(date)
KevMo
+3  A: 

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);
Jon
I'd rather make use of `Calendar#getInstance()`. The factory will return a locale dependent Calendar.
BalusC