user5849987
user5849987

Reputation:

creating an instance of Date class, not using the depreciated constructor Date(year, month, day), not using third party library

I'm trying to create an instance of the class Employee. Employee class is a class I came up myself. One of the instance variable in class Employee is Date dateOfJoining. I tried to pass the argument as new Date(2015, 10, 1) and have noticed that this constructor is depreciated. All I want is to create an instance of Date that include year, month and day. I DONT want to use third party library. Could someone please give me a hint? Thanks in advance for any help!

Employee e1 = new Employee(1, "justin", 1000, 23, new Date(2015, 10, 1));

Upvotes: 0

Views: 396

Answers (1)

beresfordt
beresfordt

Reputation: 5222

You can use java.util.Calendar, eg in java 8:

Date firstOfJan2016TwelvePmUk = new Calendar.Builder()
        .setDate(2016, 1, 1)
        .setTimeOfDay(12, 0, 0)
        .setLocale(Locale.UK).build()
        .getTime();

Or in java 7 something like:

    Calendar cal = Calendar.getInstance();
    cal.set(2016, 1, 1, 12, 0, 0);
    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = cal.getTime();

If you only want to set year month and day; java 8:

Date date = new Calendar.Builder()
        .setDate(2016, 1, 1).build()
        .getTime();

java7:

    Calendar cal = Calendar.getInstance();
    cal.set(2016, 1, 1, 12);
    Date date = cal.getTime();

Upvotes: 2

Related Questions