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

前端 未结 2 1174
鱼传尺愫
鱼传尺愫 2020-12-19 05:32

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,

相关标签:
2条回答
  • 2020-12-19 06:14

    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.

    0 讨论(0)
  • 2020-12-19 06:23

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

    0 讨论(0)
提交回复
热议问题