Kittyinsocks
Kittyinsocks

Reputation: 55

LocalDate data type in Java

I am working on an assignment where we are creating our own classes with their own attributes and methods (Constructor, Getter and Setter) and for one class I will need some attributes that use date e.g. dateOfIssue or dateOfPayment. I am trying to use the new LocalDate data type, but when I have instantiated an object from CheckingAccount and try to set a date, I don't know what format to put it in. I have tried 3 ints, e.g. 05, 06, 2010 in different orders, but it says expected.

Can anyone help?

import java.time.*;
import java.math.BigDecimal;

final public class CheckingAccount extends BankAccount {
    //Attributes
    private int checkingBookNo;
    private BigDecimal amountLastCheck;
    private LocalDate dateOfIssue;


public CheckingAccount(){
    checkingBookNo = 0;
    dateOfIssue = null;

}

public void setDateOfIssue ( LocalDate dateOfIssueIn )
{
   dateOfIssue = dateOfIssueIn;
}
}

Upvotes: 2

Views: 8888

Answers (2)

01es
01es

Reputation: 5410

Java 8 supplants java.util.Date and instead provides a much improved new Date and Time API. If the use of Java 8 is prohibited, but the use of 3rd party libraries is permitted, the JodaTime is a great option. This library was the basis for the new Java 8 Date and Time API, and can be used with earlier versions of Java.


In case of using Java 8 java.time package, the property should be of type LocalDate (or LocalDateTime is the time portion is needed). Setter and getter should accept and return object of the same type respectively.

Here're a couple of examples how to create date instances:

// the current date
LocalDate currentDate = LocalDate.now();

// 2015-02-11
LocalDate tenthFeb2014 = LocalDate.of(2015, Month.FEBRUARY, 11);

A nice tutorial on Java 8 Date/Time API is available here and here.

Upvotes: 2

peter.petrov
peter.petrov

Reputation: 39477

You've kind of misunderstood the meaning of SimpleDateFormat.

This field should be of type Date not of type SimpleDateFormat.

private SimpleDateFormat dateOfIssue;

The same goes for its setter's parameter. A SimpleDateFormat object
is not a date, it's something which allows you to parse/format
Dates from/to Strings. So that's the root cause of your problem.

Upvotes: 0

Related Questions