1 21 package net.mlw.vlh.adapter.jdbc.util.setter; 22 23 import java.sql.PreparedStatement ; 24 import java.sql.SQLException ; 25 import java.sql.Timestamp ; 26 import java.text.ParseException ; 27 import java.text.SimpleDateFormat ; 28 import java.util.Calendar ; 29 import java.util.Date ; 30 31 41 public class TimestampSetter extends AbstractSetter 42 { 43 public static final String DEFAULT_FORMAT = "MM/dd/yyyy"; 44 45 protected SimpleDateFormat formatter = new SimpleDateFormat (DEFAULT_FORMAT); 46 47 50 public int set(PreparedStatement query, int index, Object value) throws SQLException , ParseException 51 { 52 53 if (value == null || value instanceof Timestamp ) 54 { 55 Timestamp timestamp = (Timestamp ) value; 56 query.setTimestamp(index++, timestamp); 57 } 58 else if (value instanceof Date ) 59 { 60 Date date = (Date ) value; 61 Timestamp timestamp = new Timestamp (date.getTime()); 62 query.setTimestamp(index++, timestamp); 63 } 64 else if (value instanceof Calendar ) 65 { 66 Calendar calendar = (Calendar ) value; 67 Timestamp timestamp = new Timestamp (calendar.getTimeInMillis()); 68 query.setTimestamp(index++, timestamp); 69 } 70 else if (value instanceof String ) 71 { 72 Date date = formatter.parse((String ) value); 73 Timestamp timestamp = new Timestamp (date.getTime()); 74 query.setTimestamp(index++, timestamp); 75 } 76 else 77 { 78 throw new IllegalArgumentException ("Cannot convert object of type " + value.getClass().getName() + " to timestamp at position " 79 + index); 80 } 81 82 return index; 83 } 84 85 88 public void setFormat(String format) 89 { 90 formatter = new SimpleDateFormat (format); 91 } 92 } | Popular Tags |