Java Developer
Java Developer

Reputation: 1

How to convert string Date to Timestamp in Java for the format dd-MMM-yyyy?

I want to convert string Date to Timestamp in java. The following are the codes that I have written. The date value passed is in the format 19-SEP-2013.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = dateFormat.parse(tcmo.getCtsDate());
ps.setTimestamp(ctr++, new Timestamp(date.getTime());

The variable ctr is declared already. ps is the PreparedStatement object. Later codes include ps.executeUpdate().

tcmo.getCtsDate() returns the value 19-Sep-2013.

Database can accept only Timestamp in the format 2013-09-19 00:00:00.0

The exception thrown is Unparseable Date "19-SEP-2013". can anyone help me to clear this?

Upvotes: 0

Views: 12232

Answers (3)

Bohemian
Bohemian

Reputation: 425378

This is a "gotcha" that traps many programmers new to java. The format character m is for minutes and M is for months..

Your format string of "yyyy-mm-dd" is effectively years-minutes-days.

Change the format string to "yyyy-MM-dd..." and it will fix the problem.

Upvotes: 0

lealand
lealand

Reputation: 367

Try replacing the first line with

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");

This should resolve the parsing error.

Further information about SimpleDateFormat, including what are valid letters, can be found in the Oracle JavaDocs.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347334

Your format String (yyyy-mm-dd HH:mm:ss) and your input (19-SEP-2013) don't match.

A format of dd-MMM-yyyy would be required to parse the String to a Date object

For example...

try {
    String text = "19-SEP-2013";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = sdf.parse(text);
    System.out.println(text + " to " + date);
} catch (ParseException exp) {
    exp.printStackTrace();
}

Outputs...

19-SEP-2013 to Thu Sep 19 00:00:00 EST 2013

Upvotes: 2

Related Questions