0

How can I give my datamember date from the type Date a value? I added in my class the import java.util.* statement but I can't find a way to give it a value. It isn't a string like "12-11-2014" This is one of my first project with Java, so I don't have many experience. ;-)

Greetings Moleculation

import java.util.*;

public class Training
{
// data members (instance variables)
private double distance;  // in km
private double time;  // in seconden
private String type;
private Adres address;
private Date date;


public Training(int distance, int time, String type, Adres address, Date date)
{
    // initialise data members (if necessary)
    this.distance = distance;
    this.time = time;
    this.type = type;
    this.address = address;
    this.date = date;
}
// getters
public double getDistance()
{
    return distance;
}
public double getTime()
{
    return time;
}
public String getType()
{
    return type;
}
public Date getDate()
{
    return date;
}
public Adres getAddress()
{
    return address;
}

// setters

}
Moleculation
  • 1
  • 1
  • 2

3 Answers3

0

You can do -

Date date = new Date();

This will assign the current system date to date.

SagarVimal
  • 259
  • 2
  • 5
  • 12
0

Use the Calendar class instead. You can then use something similar to:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day); 

Remember, that can use the constants in the class too, e.g. :

cal.set(Calendar.MONTH, Calender.MARCH);
Rob B
  • 11
  • 2
0

Adding to SagarVimal's answer, you can use an instance of the GregorianCalendar class to represent any date:

GregorianCalendar calendar = new GregorianCalendar(int year, int month, int day);

To turn it into a Date object, use:

Date date = calendar.getTime();

Sources: http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html http://isolani.co.uk/blog/java/CreatingJavaUtilDateObjectUsingGregorianCalendar

InputUsername
  • 390
  • 1
  • 3
  • 12