0

I have an html page having a form with input type="time". This time is in 12 hr format by default.

The user will select the time and it should get stored in the MYSQL database. In my database, I have created a table with the field called "bookingTime" and its datatype is TIME.

I am trying to write the java code to store the time in the database.

The problem is, when I select the time (for Ex. 03.30 PM) on the HTML page, it is being received in the backend as "1970-01-01T20:30:00.000Z".

I am not able to parse this and store the actual time(which is 15:30:00) in the MYSQL database.

Can someone provide me the java code to do this?

RITZ XAVI
  • 3,633
  • 1
  • 25
  • 35
  • do you have the same issue while retrieving? It could be that, db stores a time zone independent value, but may be able to retrieve the date in original time zone.. – Jos Jan 06 '16 at 19:31
  • You could store the complete date/time information e.g. as long in the database. This avoids confusion with the different timezones (in DB table/ in java). In the backend you can then parse the long to a Date/time by using a [Calendar](https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) – Stefan Freitag Jan 06 '16 at 19:33
  • you might want to change that input type to something else http://stackoverflow.com/questions/13523060/html5-time-inputs-shows-12-hours – Emre Türkiş Jan 06 '16 at 19:44

2 Answers2

0

You can use a Calendar variable, so you can create a new Calendar and set the time.

After that, use a PreparedStatement to set the time as String, using SimpleDateFormat("HH:mm:ss")

Calendar myCalendar = Calendar.getInstance();
myCalendar.set(Calendar.HOUR, hour);
myCalendar.set(Calendar.MINUTE, minute);
myCalendar.set(Calendar.SECOND, second);

SimpleDateFormat sdf =  new SimpleDateFormat("HH:mm:ss" );
String time = sdf.format(  myCalendar.getTime() );   

...    
ps.setString("myTimeField", time);
Renan Ceratto
  • 130
  • 2
  • 12
0

Here I am using your String "1970-01-01T20:30:00.000Z", but it should be replaced with your expected content from that form

DateFormat formatFromHtml =  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateFormat formatterToMySQL =  new SimpleDateFormat("H:mm:ss");
Date result = formatFromHtml.parse("1970-01-01T20:30:00.000Z");
String validForTimeInMysql = formatterToMySQL.format(result);

After that, in validForTimeInMysql you get a String that can be added to MySQL

OscarBcn
  • 626
  • 4
  • 11