简体   繁体   English

将日期分为几年,几个月,几天,几小时的单独部分。 Java的

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

is there a way of organising a number of days calculated by working out the difference between two dates, into different sections eg 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. 有没有办法通过计算两个日期之间的差异来计算一些天数,分成不同的部分,例如364天,它将是:0年,11个月,30天,小时,分钟等。我认为使用逻辑运算符可能像%和/一样工作,但由于不同的月份有不同的天数,有些年份是闰年,我不知道该怎么做。 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.");
    }
}

You could effectively use Joda Time like this: Interval allows to get time interval between two dates. 您可以像这样有效地使用Joda Time: Interval允许获得两个日期之间的时间间隔。

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");

tl;dr TL;博士

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 java.time

The modern approach uses the java.time classes rather than the terrible old Date & Calendar classes. 现代方法使用java.time类而不是可怕的旧DateCalendar类。 The Joda-Time library seen in the other Answer is also supplanted by java.time . 另一个答案中看到的Joda-Time库也被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 . continent/region的格式指定适当的时区名称 ,例如America/MontrealAfrica/CasablancaPacific/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(!). 切勿使用3-4字母缩写,例如ESTIST因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

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. 如果您想要当天的第一时刻,请让java.time确定该区域中该日期的时间。 A day does not always begin at 00:00:00. 每天总是开始于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. 使用Duration类计算经过的天数(实际上是24小时的时间段),小时,分钟和秒。 For years-months-days (calendar days, not 24-hour chunks of time), use Period class. 对于年 - 月 - 日(日历日,而不是24小时的时间段),请使用Period类。

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

Generate a String object with text in standard ISO 8601 format. 使用标准ISO 8601格式的文本生成String对象。

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

PT2H3M42.725S 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. 涉及棘手的问题,例如日历天与24小时的时间段,以及天数变化的事实,例如23,24,25或其他小时数。

But if you really insist on this approach, add the ThreeTen-Extra library to your project to access the PeriodDuration class. 但是,如果您真的坚持这种方法,请将ThreeTen-Extra库添加到项目中以访问PeriodDuration类。 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. ISO-8601日历系统中结合了句点和持续时间的时间量。

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. 有关更多详细信息,请参阅Period和Duration类。

The days in a period take account of daylight saving changes (23 or 25 hour days). 一段时间内的日子考虑了夏令时的变化(23或25小时)。 When performing calculations, the period is added first, then the duration. 执行计算时,首先添加周期,然后添加持续时间。


About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用符合JDBC 4.2或更高版本的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 从哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM