Set Date in a single line

JavaDateCalendar

Java Problem Overview


According to the Java API, the constructor Date(year, month, day) is deprecated. I know that I can replace it with the following code:

Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, theYear);
myCal.set(Calendar.MONTH, theMonth);
myCal.set(Calendar.DAY_OF_MONTH, theDay);
Date theDate = myCal.getTime();

However, I would like something shorter to replace it with (ideally one to two lines).

Java Solutions


Solution 1 - Java

You could use new GregorianCalendar(theYear, theMonth, theDay).getTime():

> public GregorianCalendar(int year, int month, int dayOfMonth) > > Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

Solution 2 - Java

You could use

new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" )

Solution 3 - Java

This is yet another reason to use Joda Time

new DateMidnight(2010, 3, 5)

DateMidnight is now deprecated but the same effect can be achieved with Joda Time DateTime

DateTime dt = new DateTime(2010, 3, 5, 0, 0);

Solution 4 - Java

Calendar has a set() method that can set the year, month, and day-of-month in one call:

myCal.set( theYear, theMonth, theDay );

Solution 5 - Java

Why don't you just write a simple utility method:

public final class DateUtils {
    private DateUtils() {
    }

    public static Calendar calendarFor(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
        return cal;
    }

    // ... maybe other utility methods
}

And then call that everywhere in the rest of your code:

Calendar cal = DateUtils.calendarFor(2010, Calendar.MAY, 21);

Solution 6 - Java

tl;dr

LocalDate.of( 2015 , Month.JUNE , 7 )  // Using handy `Month` enum. 

…or…

LocalDate.of( 2015 , 6 , 7 )  // Sensible numbering, 1-12 for January to December. 

java.time

The java.time framework built into Java 8 and later supplants the troublesome old classes, java.util.Date/.Calendar.

The java.time classes use immutable objects. So they are inherently thread-safe. You will have none of the thread-safety problems mentioned on the other answers.

LocalDate

This framework included a class for date-only objects without any time-of-day or time zone, LocalDate. Note that a time zone (ZoneId) is necessary to determine a date.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );

You can instantiate for a specific date. Note that month number is a sensible range of 1-12 unlike the old classes.

LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );

Or use the enum, Month.

LocalDate localDate = LocalDate.of( 2015 , Month.JUNE , 7 );

Convert

Best to avoid the old date-time classes. But if you must, you can convert. Call new methods added to the old classes to facilitate conversions.

In this case we need to specify a time-of-day to go along with our date-only value, to be combined for a java.util.Date object. First moment of the day likely makes sense. Let java.time determine the time of that first moment as it is not always 00:00:00.0.

We also need to specify a time zone, as the date varies by time zone.

ZoneId zoneId = zoneId.of( "America/Montreal" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

An Instant is a basic class in java.time, representing a moment on the timeline in UTC. Feed an Instant to static method on Date to convert.

Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Solution 7 - Java

Date date = new DateTime(2014, 6, 20, 0, 0).toDate();

DateTime is from Joda.org https://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html

Solution 8 - Java

Use the constructor Date(year,month,date) in Java 8 it is deprecated:

Date date = new Date(1990, 10, 26, 0, 0);

The best way is to use SimpleDateFormat

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("26/10/1985");

you need to import import java.text.SimpleDateFormat;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhibernateView Question on Stackoverflow
Solution 1 - JavaaioobeView Answer on Stackoverflow
Solution 2 - JavatangensView Answer on Stackoverflow
Solution 3 - JavaSean OwenView Answer on Stackoverflow
Solution 4 - Javamartin claytonView Answer on Stackoverflow
Solution 5 - JavaJesperView Answer on Stackoverflow
Solution 6 - JavaBasil BourqueView Answer on Stackoverflow
Solution 7 - JavaChengView Answer on Stackoverflow
Solution 8 - JavaGAbriel lopezView Answer on Stackoverflow