99maas 99maas - 2 years ago 113
Java Question

How to convert two String variables to date and timestamp column to insert into database

I need your help in getting the proper format to insert the date and time informaiton which is retrieved from two different string variables from the database and to insert them (date and time) into Date and Time column in an another table. The date is retrieved from the agreement date column which is:

String agreement_date = "";
agreement_date=rs.getString("agr_date"); //format DD-MON-YYYY ex. 22-May-2014

And the time is retrieved from:

String frm_time = rs.getString("FRM_TIME"); //format HH:MI ex.7:20

So now I need to combine both columns into one variable and to insert them in database column called transaction_dt_time and its type is dateTime(format dd/MM/YYYY HH:MI:SS AM/PM), So how can I do that?

Answer Source

I understand you are fetching the values in the resultset from a database. generally date and time are stored in database according to the datatype. Recommend to use a rs.getDate() and rs.getTime() to fetch these values instead of a String datatype.

Here is a sample code for your conversion

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo  {

    public static void main(String[] args) {
            String date = "22-May-2015";
            String time = "7:20";
            String yourString = date+ " "+ time;
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
            Date parsedDate = dateFormat.parse(yourString);
            Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
        }catch(Exception e){
            //this generic but you can control another types of exception
            // look the origin of excption 

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download