The correct way to set and get hours, minutes, seconds

I am trying to get some information from a database, and then using this information to get some statistics.

I want to get statistics based on the interval of hours, so I created a HashSet consisting of two hours of Integer and data.

To get the correct hour, I need to get the time from the database. So I need to create some kind of data / calendar object.

Now, since Date out of date, I need to find a new way to set the clock.

Does anyone know how I can achieve this?

So far this solution works:

 Calendar time = Calendar.getInstance(); time.setTime(new Date(2012, 11, 12, 8, 10)); int hour = time.get(Calendar.HOUR); System.out.println(hour); 

But, as stated above, the date is out of date, so I want to find out the β€œright” way to do this.

+4
source share
2 answers

Using java.util.Calendar

 Calendar c = Calendar.getInstance(); c.set(Calendar.DATE, 2); c.set(Calendar.HOUR_OF_DAY, 1); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); 

Or use Joda Time http://joda-time.sourceforge.net/ .

+9
source

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.

+2
source

Source: https://habr.com/ru/post/1445497/