2

Im getting a String from my Jsp from a input

<form method=POST action="ResultServlet">
                Enter date
                <input type="datetime" name="StartEvent" >
                <input type="datetime" name="StopEvent" >


           <input type="submit" name="PostThis" value="Show" class="f-halfbutton">

And i try to format or parse it into date so i can send it to my database.

String stopDateStr = request.getParameter("StopEvent");
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssZ");
        Date to = new Date();
        try {
            to = sdf.parse(stopDateStr);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(from);
        System.out.println(to );

When i print the string i get the correct format like this 2015-05-19 15:19:12

i want to keep the same format just change it to date instead of string. but after my format my string or date that it should be now looks like this Mon Jan 19 15:19:12 CET 2015

i tried to read here on solutions but nothing seem to work for me.

i've been reading on oracle on the simpledateformatter to know what letters to use to get numbers but doesnt seem to work.

anyone got a good solutions for this?

2
  • i've tried diffrent kind of format even the one that sohuld be corrent "yyyy-mm-dd hh:mm:ss" but still the same output Mon Jan 19 15:19:12 CET 2015 Commented May 21, 2015 at 9:21
  • The format is not magically attached to the Date variable. In fact it contains pretty much only the number of ms since the start of the epoch. If you want to format it you need another instance of SimpleDateFormat to format the date. But why bother, if you want to insert it in a database, the Date variable is all you need. Commented May 21, 2015 at 9:26

1 Answer 1

1

The formatting is irrelevant when you insert it in the database. You just need to get the correct Date from the string and then insert it into the database. When you retrieve the value from the database you can format it anyway you like...

You can use something like this:

String date = "your_date_formatted";
Date dt= new SimpleDateFormat("date_format").parse(date);
java.sql.Date sqlDate = new java.sql.Date(dt.getTime()); 

Connection con = ...;
PreparedStatement p = con.prepareStatement("insert into table(date_field) values(?))");
p.setDate(1, dt);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.