0

I am working on my MySQL project and I have one problem. I have made one JSpinner that shows current date and time. Now I want to save that date and time in one datetime variable for later use, but problem is when I save value from JSpinner into my datetime variable its not in 'YYYY-MM-DD HH:MM:SS' format. Instead of that my datetime variable contains this: 'Sat Aug 17 19:07:03 CEST 2013'. I want to save only numbers in classic 'YYYY-MM-DD HH:MM:SS' format because my database on my server accepts only data in that format, but I dont know how to cast it. Please help!

Here is my code:

String datum_vrijeme;
SpinnerDateModel s1 = new SpinnerDateModel();
spinner1 = new JSpinner(s1);
JSpinner.DateEditor d1 = new JSpinner.DateEditor(spinner1, "yyyy/MM/dd   HH:mm:ss");
spinner1.setEditor(d1);
Object sp = spinner1.getValue();
datum_vrijeme=sp.toString();
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Mahir Duraković
  • 135
  • 1
  • 23

1 Answers1

1

You can get the java.util.Date object, which is one step closer to your MySQL database, instead of a String.

Date date = (Date) spinner1.getValue();
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • Sorry but I am using JDBC connector and I need to write my sql query so I need to have my datetime in string format so I can concatenate it with my string query to finally execute it to update my database row... – Mahir Duraković Aug 17 '13 at 17:42
  • 1
    You should do as Martijn suggests, and pass the Date object as a parameter of a [PreparedStatement](http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html). – VGR Aug 17 '13 at 17:49
  • @MahirDuraković: That is BAD practice! Search for PreparedStatements and SQL Injection and you will know why. Prepared Statements do support Date objects. – Martijn Courteaux Aug 17 '13 at 17:53
  • I tried your suggestions but I have same problem again. My Date variable is in this format: 'Sat Aug 17 19:07:03 CEST 2013', I want it in classic 'YYYY-MM-DD HH:MM:SS' format – Mahir Duraković Aug 17 '13 at 18:06
  • @Mahir Duraković have to test if required to convert util.Date to sql.Date or to Timestampt up to you. btw must be a bunch Q&A here about, note in all cases you need to separate logics for Swing (JSpinner), Java Essential Classes(util.Date) and JDBC (DateTime/Timestampt) – mKorbel Aug 17 '13 at 18:24