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


public class StringtoDate {
    public static void main (String args[]){
        String inputDate = "04.11.2013 11:14:45 GMT 00:00";
        Date dat = convertStringToDate(inputDate);
    }
    public static Date convertStringToDate(String inDate){
    SimpleDateFormat sdf = new SimpleDateFormat("mm.dd.yyyy hh24:mm:ss");
        Date date = new Date();
         try {
             date = sdf.parse(inDate);

         } catch (Exception e) {
          e.printStackTrace();
        }
         return date;
    }
}

my input String is of type String ("04.11.2013 11:14:45 GMT 00:00"),
I m trying to convert to a type Date and which should be of foramt ("mm.dd.yyyy hh24:mi:ss") , and output of the DAte should look like ("3/7/2013 12:33:15.000000000 PM").
but i m getting exception ,

    java.text.ParseException: Unparseable date: "04.11.2013 11:14:45 GMT 00:00"
at StringtoDate.convertStringToDate(StringtoDate.java:14)
at StringtoDate.main(StringtoDate.java:8)

please help me to get the correct results.

Dani AI

Generated

is right about using M for month and H for 24-hour time. The remaining parse error is the zone tail. SimpleDateFormat accepts either GMT+0000 with a pattern like 'GMT'Z, or an ISO-style offset such as +00:00 with the X patterns. A bare GMT 00:00 (no sign, colon in the offset) does not match, so parsing fails. Normalize that piece or ask the source to include a sign. Also, per , Date has no format; only the String representation does. See the pattern rules in the JDK docs: SimpleDateFormat pattern letters. (docs.oracle.com)

Here is a small, Java 7–compatible normalizer + parser:

static Date parseInput(String s) throws ParseException {
  Matcher m = Pattern.compile("(.+)\\sGMT\\s([+-]?\\d{2}):(\\d{2})$").matcher(s);
  if (!m.matches()) throw new ParseException("Unexpected tz format", 0);
  String hh = m.group(2); if (!hh.startsWith("+") && !hh.startsWith("-")) hh = "+" + hh;
  String normalized = m.group(1) + " GMT" + hh + m.group(3); // -> e.g., GMT+0000
  return new SimpleDateFormat("MM.dd.yyyy HH:mm:ss 'GMT'Z", Locale.US).parse(normalized);
}

To pass the value to your stored procedure, convert to java.sql.Timestamp and, if you need to drop fractional seconds, zero the nanos before binding:

Date date = parseInput(input);
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(0); // truncate fractional seconds
try (CallableStatement c = conn.prepareCall("{call my_proc(?)}")) {
  c.setTimestamp(1, ts); // or supply a Calendar if the proc expects a specific zone
  c.execute();
}

Timestamp#setNanos controls the fractional second, and JDBC provides setTimestamp(..., Calendar) when you must pin the timezone at bind time: see Timestamp Javadoc and PreparedStatement.setTimestamp. (docs.oracle.com)

(If you prefer ’s approach, you can also pass the original String and let the DB parse it.)

Recommended Answers

All 11 Replies

The main issue is actually with your format string; for month, you should use capitalized letter M. Similarly, for 24-hour time going from 00 to 23, you need to use capital H. To get the time zone in the format you want, use the capital letter Z twice.

"MM.dd.yyyy HH:mm:ss ZZ"

But

sdf1.format(date)

would return Stringbuffer or string .
i need the format in DATE or timestamp

have you checked the other methods available in SimpleDateFormat?

You seeem to be confused about the Date class.
A Date object represents an instant in time, and has methods to access it. It does NOT have a format. When you convert a Date to or from a String that's when a format is applied.

The main objective here is to pass my Date to Storedprocedure , where the stored procedure is mapped to Timestamp variable.

yeah i correct it, not the Date format . want it in Date object .

You have a String in a known format and you want to convert that to a Date object - yes?
If so your first code was the right approach. Did you fix the format specification as noted by Schol-R-LEA

if your main objective is to pass it to a stored procedure, pass it as is (meaning, as a string) and write the stored procedure in such a way that it does the conversion.
Much more efficient, as it eliminates the implicit conversion of a Java Date to a database date, and pushes the conversion to the database server, which typically is much better at such tasks (faster...) than the application server.

the format of Timestamp variable is** yyyy-mm-dd hh:mm:ss.fffffffff**(check it http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html )
in that case why don't you directly send data in Timestampl instead of doing all this

date = sdf.parse(inDate);
new java.sql.Timestamp(date.getTime())

Just an opinion,not sure about its efficiency.

OK, thanks guys, tried using java.sql.timestamp , but still was not able to truncate the millisec from the timestamp object .
now changing the stored procedure .
if more doubts i ll start a new discussion about the stored procudure.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.