Should we use a Date object in java?

Should we use the java.util.Date object in java? It has so many legacy methods that are a little unnecessary to use a sophisticated method for something that should be so simple.

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

This should be the best way ...

+3
source share
4 answers

The javadoc for each method says that it has been replaced. 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);
}
+2
source

This may be a matter of preference, but I'm using Joda Time .

DateTime API Joda Time, DateTime#dayOfMonth , .

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'
+5

The Java Date class is known as confusing and clumsy. I would recommend looking at the popular Joda Time library:

http://joda-time.sourceforge.net/

+3
source

No, you should no longer use java.util.Date.

GregorianCalendar is an alternative 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);
+3
source

Source: https://habr.com/ru/post/1743092/


All Articles