Organise number of days into separate sections for year, months, days, hours. Java

巧了我就是萌 提交于 2019-12-20 03:57:11

问题


is there a way of organising a number of days calculated by working out the difference between two dates, into different sections e.g. for 364 days it would be: 0 years, 11 months, 30 days, hours, minutes etc. I thought using logical operators may work like % and / but as different months have different amounts of days and some years are leap years i'm not sure how to do it. Any help would be much appreciated. My code:

import java.util.*;

public class CleanDate {

    public static void main(String[] args) {
        Calendar cDate = GregorianCalendar.getInstance();
        cDate.set(2011, 0, 31, 00, 00, 00);
        Date date1 = cDate.getTime();
        Date date2 = new Date();
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar2.setTime(date2);
        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        long diffSeconds = diff / 1000;
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);
        System.out.println("Time in minutes: " + diffMinutes + " minutes.");
        System.out.println("Time in hours: " + diffHours + " hours.");
        System.out.println("Time in days: " + diffDays + " days.");
    }
}

回答1:


You could effectively use Joda Time like this: Interval allows to get time interval between two dates.

DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println(period.getYears()+" years, "
period.getMonths()+" months, "+period.getWeeks()+" weeks, "+period.getDays()+", days");



回答2:


tl;dr

Duration.between(          // Represent a span-of-time unattached to the timeline, on scale of days-hours-minutes-seconds.
    ZonedDateTime          // Represent a moment in the wall-clock time used by the people of a particular region (a time zone). 
    .of( 2011 , 1 , 31 , 0 , 0 , 0 , 0 , ZoneId.of( "Africa/Tunis" ) )
    ,
    ZonedDateTime.of( … ) 
)                          // Returns a `Duration` object.
.toDaysPart()              // Or `toHoursPart`, `toMinutesPart`, `toSecondsPart`, `toNanosPart`. These return either a `long` or an `int`. 

java.time

The modern approach uses the java.time classes rather than the terrible old Date & Calendar classes. The Joda-Time library seen in the other Answer is also supplanted by java.time.

Specifying a date and a time-of-day requires a time zone to determine an exact moment. For any given moment both the date and the time-of-day vary around the globe by zone.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;

If you want the first moment of the day, let java.time determine the time-of-day for that date in that zone. A day does not always begin at 00:00:00.

LocalDate ld = LocalDate.of( 2011 , Month.JANUARY , 31 ) ;
ZonedDateTime start = ld.atStartOfDay( z ) ;  // Let java.time determine the first moment of the day. Never assume 00:00:00.

Calculate elapsed days (actually 24-hour chunks of time), hours, minutes, and seconds using Duration class. For years-months-days (calendar days, not 24-hour chunks of time), use Period class.

ZonedDateTime stop = … ;
Duration d = Duration.between( start , stop ) ;

Generate a String object with text in standard ISO 8601 format.

String output = d.toString() ;  // Generate standard ISO 8601 text.

PT2H3M42.725S

Extract the various pieces.

long days = d.toDaysPart() ;       // 24-hour chunks of time, *not* calendar days.
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
int nanos = d.toNanosPart() ;      // Fractional second as a count of nanoseconds, from 0 to 999,999,999.

Years-months-days versus days-hours-minutes-seconds

If you think about it, trying to represent a span-of-time in terms of years-months-days-hours-minutes-seconds rarely makes sense. There are tricky issues involved such as calendar days versus 24-hour chunks of time, and the fact that days vary in length such as 23, 24, 25 or other number of hours long.

But if you really insist on this approach, add the ThreeTen-Extra library to your project to access the PeriodDuration class. This class attempts to combine the two concepts.

An amount of time in the ISO-8601 calendar system that combines a period and a duration.

This class models a quantity or amount of time in terms of a Period and Duration. A period is a date-based amount of time, consisting of years, months and days. A duration is a time-based amount of time, consisting of seconds and nanoseconds. See the Period and Duration classes for more details.

The days in a period take account of daylight saving changes (23 or 25 hour days). When performing calculations, the period is added first, then the duration.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.



来源:https://stackoverflow.com/questions/12612094/organise-number-of-days-into-separate-sections-for-year-months-days-hours-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!