3

im getting the SQL Server datetime (1 Jan 2013) form the SqlRowSet like

while (rs.next()) {
 myBean.setDateProp(rs.getString(4));
}

the type of myBean DateProp is java.util.Date, is there a way to convert (1 Jan 2013) to java Date representation.

i have tried the following code

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
Date date=new Date();        
    try {
        date = sdf.parse("1 Jan 2013");           
    } catch (Exception e) {
        e.printStackTrace();

    }       

and i get the ParseException

SEVERE: java.text.ParseException: Unparseable date: "1 Jan 2013"

any directions...

6
  • i have tried the following code what happened after? have you got any exception? Commented Dec 20, 2012 at 8:01
  • 3
    Why are you using rs.getString() instead of rs.getDate() ? Commented Dec 20, 2012 at 8:02
  • 1
    Why are you using the format dd-MMM-yyyy HH:mm:ss.SSS when your date string looks like 1 Jan 2013? It's obvious that the format of the string isn't what you're using. Commented Dec 20, 2012 at 8:03
  • @PradeepSimha i get the ParseException Commented Dec 20, 2012 at 8:04
  • @Charlie i tried that but the format in SQL server db is DateTime so it throws an exception stating no date was found Commented Dec 20, 2012 at 8:05

4 Answers 4

6

try this -

SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
Date date=new Date();        
try {
    date = sdf.parse("1 Jan 2013");           
}catch (Exception e) {
    e.printStackTrace();
}   
Sign up to request clarification or add additional context in comments.

3 Comments

that almost worked the parsing is done ok but when it is converted to java date it shows me Tue Jan 01 00:00:00 PKT 2013
dont print java.util.Date object. print formatted string. lyk - System.out.println(sdf.format(date));
im printing the formatted string and its printing fine but then i have to assign the value to date property of my model ...
2

Try

while (rs.next()) {
 myBean.setDateProp(rs.getDate(4));
}

2 Comments

i tried that but the db server format is datetime so it give me the error that no date was found at index 4
Sounds suspicious. Anyway, try rs.getTimestamp(4) then.
2
    @Test
    public void test() throws ParseException {

        String dateString = "1 Jan 2013";
        String dateString2 = "11 Jan 2013";
        SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy");


        sdf.parse(dateString);
        sdf.parse(dateString2);
    }

Comments

1

You need to modify your Date formatter string to

SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");

as your date string is in this format

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.