Jose Conde
Jose Conde

Reputation: 171

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

It has to be better way...

Upvotes: 3

Views: 988

Answers (4)

Michael Mrozek
Michael Mrozek

Reputation: 175335

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

Upvotes: 2

Anthony Forloney
Anthony Forloney

Reputation: 91776

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'

Upvotes: 5

Jonathan Holloway
Jonathan Holloway

Reputation: 63662

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

Upvotes: 3

Andy White
Andy White

Reputation: 88345

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/

Upvotes: 3

Related Questions