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 )?

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 value
And you're done. Simple, right? The getTime().getTime() is particularly annoying, but that's the way it is.
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact