How can I generate a java.sql.Timestamp from text fields formatted as MM/DD/YYYY and/or HH:MM:SS ( Month/Day/Year - Hours/Minutes/Seconds )?
Created May 4, 2012
Joe Sam Shirah Let's assume that the data has been parsed ( probably with StringTokenizer ) validated and converted ( probably with Integer.parseInt() ) to the ints MM, DD, YYYY and HH, MM, SS. Since the Timestamp constructor that takes these values has been deprecated, the blessed way is:
GregorianCalendar cal = new GregorianCalendar( YYYY, MM - 1, DD, HH, MM, SS );
OR
Calendar cal = Calendar.getInstance(); cal.set( CALENDAR.YEAR, YYYY ); cal.set( CALENDAR.MONTH, MM - 1 ); ... cal.set( CALENDAR.SECOND, SS );
Then, for either,
cal.set( CALENDAR.MILLISECOND, 0 ); // or other value Timestamp ts = new Timestamp( cal.getTime().getTime() ); ts.setNanos( 0 ); // or other valueAnd you're done. Simple, right? The getTime().getTime() is particularly annoying, but that's the way it is.