将DateFormat转换为Date

时间:2017-09-04 10:25:41

标签: java sql date

我有这个代码。游戏类中的基准是DateFormat,它需要是DateFormat,但在sql中我需要设置Date。如何在这行代码中将DateFormat转换为Date?

--- a/Makefile.am
+++ b/Makefile.am

游戏课程:

    try{

        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/internacionalizacija?useUnicode=true&characterEncoding=UTF-8", "root", "");

        String sql = "INSERT INTO utakmice(tim1, tim2, datum) VALUES(?,?,?)";
        PreparedStatement stmt = conn.prepareStatement(sql);
        //stmt.execute("set names 'utf8'");

        stmt.setString(1, utakmice.getTim1());
        stmt.setString(2, utakmice.getTim2());
        stmt.setDate(3, utakmice.getDatum());

我从JFrame获取日期,这里是代码:

public class Games {
    private String tim1;
    private String tim2;
    private DateFormat datum;

    public Utakmice(String tim1, String tim2, DateFormat datum) {
        this.tim1 = tim1;
        this.tim2 = tim2;
        this.datum = datum;
    }


    public void setTim1(String tim1) {
        this.tim1 = tim1;
    }

    public String getTim1() {
        return tim1;
    }

    public void setTim2(String tim2) {
        this.tim2 = tim2;
    }

    public String getTim2() {
        return tim2;
    }

    public void setDatum(DateFormat datum) {
        this.datum = datum;
    }

    public DateFormat getDatum() {
        return datum;
    }
}

1 个答案:

答案 0 :(得分:1)

您目前正在DateFormat的日期选择器中获得JFrame。你刚刚使用了错误的getter,你应该找到一个getDate()getSelectedDate(),...返回DateLocalDate,...

您正在使用DateChooserCombo。还没有找到javadoc,但我发现source code显示它提供了

public Calendar getSelectedDate() { 
    return chooser.getSelectedDate(); 
} 

返回Calendar,您可以使用Calendar.getTime()

从中获取Date

因此,不要使用DateFormat datum,而是将其更新为Date datum并将您的JFrame更改为

Date datum = txtDate.getSelectedDate().getTime(); //Might be null if nothing selected !!

豆子:

public class Games{
    private String tim1;
    private String tim2;
    private Date datum; //CHANGED HERE

    //getter and setter
}

仅供参考:

目前,已恢复的DateFormat用于使用Date.format(Date)Date.parse(String)创建或字符串Date

以下是使用SimpleDateFormatDateFormat的子类,允许创建自己的模式的简单示例,有关详细信息,请参阅文档)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//Convert a String into a Date (matching the pattern above
Date d = sdf.parse("2017-09-20");
//Convert a Date into a String(matching the pattern above
String s = sdf.format(d);