getting value from jDateChooser and saving to MS sql DB

醉酒当歌 提交于 2019-12-06 10:29:50

问题


I have two jDateChooser on my dialog , I want to save to MS-SQL DB having issue with that data types. Any idea how to fix this issue ! I can only do this when i convert data type to nvarchar in DB and convert the value to string which returns from jDateChooser.

// I can save in this way but I it doesn't use jDateChooser;

   java.util.Date utilDate = new java.util.Date();
   java.sql.Date sqldate = new java.sql.Date(utilDate.getTime());

// I cant save the date with jDateChooser

    java.sql.Date sqldate = new java.sql.Date(jDateChooser3.getDate());

// Only Way I found

  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

  String sd = dateFormat.format(jDateChooser3.getDate());

  obj.setStartDate(sd);

//


回答1:


Judging from the code you posted it looks like jDateChooser3.getDate() returns a java.util.Date instance while the java.sql.Date(millis) constructor expects the date/time as a long milliseconds value.

Use this code and it will work:

java.sql.Date sqldate = new java.sql.Date(jDateChooser3.getDate().getTime());

Since it comes from a date chooser component, invalid input most likely results in null returned date, so you might want to also check on that:

java.util.Date d = jDateChooser3.getDate();
if (d == null) {
    System.out.println("No date specified!");
} else {
    java.sql.Date sqldate = new java.sql.Date(d.getTime());
    // Do something with sqldate
}



回答2:


Right click on jDateChooser. Go to the Properties and dateFormatString. Set this format: dd-MM-yyyy.



来源:https://stackoverflow.com/questions/23564363/getting-value-from-jdatechooser-and-saving-to-ms-sql-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!