0

I am trying to make a getter for a JTextfield, the code looks like this

public Date getStartDate() {

    return textFieldStartDate.getText();
}

I get the error

 Type mismatch: cannot convert from String to Date

The problem is obvious, however i dont know how to solve it. I have been searching alot, but couldnt find a simple answer.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mads Hjorth
  • 439
  • 1
  • 9
  • 23
  • 1
    http://stackoverflow.com/questions/999172/how-to-parse-a-date – Misch Dec 04 '14 at 12:02
  • Of course you are having a `Date` field so the return type should be `Date` as well but you are returning `String`. You just need to convert the String to Date and return it. – Stanley Mungai Dec 04 '14 at 12:13

2 Answers2

1

Try this:

public Date getStartDate() {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = formatter.parse(textFieldStartDate.getText());
    return date;
}
Stanley Mungai
  • 4,044
  • 30
  • 100
  • 168
  • Worked perfect. However i changed the format to MM-dd-yyyy, but it results ex. ""Oct 1, 2014 12:00:00 AM" and i want it in ex. "1-10-2014". Why is that not working? btw thanks for the help. – Mads Hjorth Dec 05 '14 at 14:27
0

change your method to

    public Date getStartDate() {

    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
    Date textDate= formatter.parse(textFieldStartDate.getText());
    return textDate;
    }
VaibJ
  • 84
  • 5