Retrieving a datetime from a database
Retrieving datetimes from a database has been reviewed in hundreds of responses. Please find StackOverflow. Focus on java.sql.Timestamp .
To read the topic heading Questions, read on.
Joda time
Much easier if you use Joda-Time or the java.time package bundled with Java 8 (inspired by Joda-Time). The java.util.Date and .Calendar classes bundled with Java are known to be unpleasant, confusing, and erroneous.
The time zone is crucial. Unlike java.util.Date, Joda-Time and java.time assign a time zone to their date objects.
Here is sample code showing several ways to set the time of day in a Joda-Time 2.5 DateTime object.
DateTimeZone zoneMontreal = DateTimeZone.forID( "America/Montreal" ); // Specify a time zone, or else the JVM current default time zone will be assigned to your new DateTime objects. DateTime nowMontreal = DateTime.now( zoneMontreal ); // Current moment. DateTime startOfDayMontreal = nowMontreal.withTimeAtStartOfDay(); // Set time portion to first moment of the day. Usually that means 00:00:00.000 but not always. DateTime fourHoursAfterStartOfDayMontreal = startOfDayMontreal.plusHours( 4 ); // You can add or subtract hours, minutes, and so on. DateTime todayAtThreeInAfternoon = nowMontreal.withTime(15, 0, 0, 0); // Set a specific time of day.
Conversion
If you absolutely need a java.util.Date object, convert from Joda-Time.
java.util.Date date = startOfDayMontreal.toDate();
To go from juDate to Joda-Time, pass the Date object to the Joda-Time DateTime constructor.
source share