Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JTextfield的getter,作为日期_Java_Swing_Jtextfield_Getter - Fatal编程技术网

Java JTextfield的getter,作为日期

Java JTextfield的getter,作为日期,java,swing,jtextfield,getter,Java,Swing,Jtextfield,Getter,我试图为JTextfield创建一个getter,代码如下所示 public Date getStartDate() { return textFieldStartDate.getText(); } 我得到了错误 Type mismatch: cannot convert from String to Date 问题很明显,但我不知道如何解决它。我一直在搜索,但找不到简单的答案。试试这个: public Date getStartDate() { SimpleDateFormat

我试图为JTextfield创建一个getter,代码如下所示

public Date getStartDate() {

    return textFieldStartDate.getText();
}
我得到了错误

 Type mismatch: cannot convert from String to Date
问题很明显,但我不知道如何解决它。我一直在搜索,但找不到简单的答案。

试试这个:

public Date getStartDate() {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = formatter.parse(textFieldStartDate.getText());
    return date;
}
将您的方法更改为

    public Date getStartDate() {

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

当然,您有一个
Date
字段,因此返回类型也应该是
Date
,但您返回的是
String
。您只需要将字符串转换为日期并返回它。请提供此操作的说明/您更改了什么。与上面的答案没有任何不同。我们在同一时间发布了答案。工作正常。但是,我将格式更改为MM dd yyyy,但结果为“2014年10月1日12:00:00 AM”,我希望格式为“2014年10月1日”。为什么不起作用?顺便说一句,谢谢您的帮助。