Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way to set and get hour, minutes, sec

I am trying to get some information out of a database and then using that information to get some statistics.

I want to get statistics based on an interval of hours, therefore I have a created a HashSet made up of two Integers hour and data.

In order to get the correct hour I need to get the time out of the database. Therefore I need to create some sort of data / calendar object.

Now since Date has been deprecated I need to find a new way to set the hours.

Does anyone know how i can achive 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 date has been deprecated so I want to learn the "correct" way to do it.

like image 344
Marc Rasmussen Avatar asked Nov 12 '12 12:11

Marc Rasmussen


2 Answers

Using the 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/.

like image 86
Aleksandr M Avatar answered Sep 28 '22 15:09

Aleksandr M


Getting Date-Time From Database

Getting date-time from a database has been addressed in hundreds of answers. Please search StackOverflow. Focus on java.sql.Timestamp.

To address the topic of your Question’s title, read on.

Joda-Time

Far easier if you use either Joda-Time or the java.time package bundled with Java 8 (inspired by Joda-Time). The java.util.Date & .Calendar classes bundled with Java are notoriously troublesome, confusing, and flawed.

Time zone is crucial. Unlike java.util.Date, both Joda-Time and java.time assign a time zone to their date-time objects.

Here is some example code to show multiple ways to set the time-of-day on a Joda-Time 2.5 DateTime object.

DateTimeZone zoneMontreal = DateTimeZone.forID( "America/Montreal" );  // Specify a time zone, or else the JVM's 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.

Converting

If you absolutely need a java.util.Date object, convert from Joda-Time.

java.util.Date date = startOfDayMontreal.toDate();

To go from j.u.Date to Joda-Time, pass the Date object to constructor of Joda-Time DateTime.

like image 42
Basil Bourque Avatar answered Sep 28 '22 16:09

Basil Bourque