简体   繁体   English

使用 Java 中的 OffsetDateTime 计算“时间前”

[英]Calculating "time ago" using OffsetDateTime in Java

I currently have this code:我目前有这个代码:

public static String getTimeAgo(OffsetDateTime dateArg) {
    Instant instantNow = Instant.now();
    Instant instantThen = dateArg.toInstant();
    Duration comparedDuration = Duration.between(instantThen, instantNow);

    LocalDate localDate = dateArg.toLocalDate();
    LocalDate localDateToday = LocalDate.now(ZoneId.systemDefault());
    Period comparedPeriod = Period.between(localDate, localDateToday);

    ZonedDateTime zdt1 = ZonedDateTime.ofInstant(instantThen, ZoneId.systemDefault());
    ZonedDateTime zdt2 = ZonedDateTime.ofInstant(instantNow, ZoneId.systemDefault());
    Calendar calendarFetched = GregorianCalendar.from(zdt1);
    Calendar calendarNow = GregorianCalendar.from(zdt2);

    Instant d1i = Instant.ofEpochMilli(calendarFetched.getTimeInMillis());
    Instant d2i = Instant.ofEpochMilli(calendarNow.getTimeInMillis());

    LocalDateTime startDateWeek = LocalDateTime.ofInstant(d1i, ZoneId.systemDefault());
    LocalDateTime endDateWeek = LocalDateTime.ofInstant(d2i, ZoneId.systemDefault());

    long weeksCalc = ChronoUnit.WEEKS.between(startDateWeek, endDateWeek);


    String s = "";
    if(comparedPeriod.getYears() > 0) {
        s += comparedPeriod.getYears() + " year" + ((comparedPeriod.getYears() == 1) ? " " : "s ");
    }

    if(weeksCalc > 4){
        s += comparedPeriod.getMonths() + " month" + ((comparedPeriod.getMonths() == 1) ? " " : "s ");

    }
    else{
        s += weeksCalc + " weeks ";

    }

    if (comparedPeriod.getDays() > 0){
        s += comparedPeriod.getDays() + " day" + ((comparedPeriod.getDays() == 1) ? " " : "s ");
    }

    if (comparedDuration.toHoursPart() > 0) {
        s += comparedDuration.toHoursPart() + " hour" + ((comparedDuration.toHoursPart() == 1) ? " " : "s ");
    }
    else{
        if(comparedDuration.toMinutesPart() > 0){
            s += comparedDuration.toMinutesPart() + " minute" + ((comparedDuration.toMinutesPart() == 1) ? " " : "s ");
        }

        else s += comparedDuration.toSecondsPart() + " seconds "; // lol lets just end it here...
    }

    return s + "ago";
}

The goal is to display "time ago" based off from given OffsetDateTime argument.目标是根据给定的OffsetDateTime参数显示“时间前”。 This is to show the year, month, weeks, days, hours, minutes, all the way down to seconds, if said time units were not at 0 .这是为了显示年、月、周、日、小时、分钟,一直到秒,如果所述时间单位不是0 But I am having trouble calculating the month as the result always come back as 0 , while having an "s" indicating that it is not truly 0 .但是我在计算月份时遇到了麻烦,因为结果总是返回为0 ,同时有一个“s”表示它不是真正的0

For example, running System.out.println(Utils.getTimeAgo(OffsetDateTime.parse("2020-12-13T15:54:43.971273200-05:00"))) displays 1 year 0 months 1 hour ago as its output...例如,运行System.out.println(Utils.getTimeAgo(OffsetDateTime.parse("2020-12-13T15:54:43.971273200-05:00")))1 year 0 months 1 hour ago显示为其 output...

If you think in it, you'll realize that rarely does it often dies not make sense to represent a span of time as years-months-days-hours-minutes-seconds.如果你仔细想想,你会发现,用年-月-日-小时-分钟-秒来表示时间跨度通常是没有意义的。

That is why java.time splits out the scales I to two separate classes:这就是为什么java.time将刻度 I 分成两个单独的类:

  • Period years-months-days Period年-月-日
  • Duration hours-minutes-seconds Duration小时-分钟-秒

If you insist on combing the two scales, I suggest adding the ThreeTen-Extra library to your project.如果你坚持要把这两个尺度结合起来,我建议在你的项目中加入ThreeTen-Extra库。 This provides the PeriodDuration class.这提供了PeriodDuration class。

OffsetDateTime odtThen = … ;
OffsetDateTime odtNow = OffsetDateTime.now( odtThen.getOffset() ) ;
PeriodDuration pd = PeriodDuration.between( odtThen, odtNow ) ;

Interrogate to obtain each part.询问以获得每个部分。 One way to do that is to loop on the list returned from PeriodDuration#getUnits .一种方法是循环从PeriodDuration#getUnits返回的列表。


As commented , stop using Calendar class.评论,停止使用Calendar class。 Along with Date & SimpleDateFormat , these terrible date-time classes were entirely supplanted by the java.time classes defined in JSR 310.连同DateSimpleDateFormat ,这些糟糕的日期时间类完全被 JSR 310 中定义的java.time类所取代。

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

相关问题 Java 8+ 时间戳问题与 OffsetDateTime - Java 8+ Time stamp issue with OffsetDateTime 如何在 Java 中计算“时间前”? - How to calculate “time ago” in Java? 如何将 org.threeten.bp.OffsetDateTime 转换为 java.time.OffsetDateTime? - How can I convert a org.threeten.bp.OffsetDateTime to java.time.OffsetDateTime? 如何将java.sql.Timestamp转换为java.time.OffsetDateTime? - How to convert java.sql.Timestamp to java.time.OffsetDateTime? 在SQLite数据库中存储java.time.OffsetDateTime的推荐方法 - Recommended way to store java.time.OffsetDateTime in SQLite Database Java OffsetDateTime.parse() 将额外的零添加到时间 - Java OffsetDateTime.parse() adds extra zeros to time 使用 java.time.Instant 来表示 DateTime 而不是 OffsetDateTime - Use java.time.Instant to represent DateTime instead of OffsetDateTime 如何将带时区的 PostgreSQL 时间戳转换为 Java Instant 或 OffSetDateTime? - How to convert PostgreSQL timestamp with time zone to Java Instant or OffSetDateTime? 将 ISO 8601 时间戳字符串转换为 java.time.OffsetDateTime - Converting ISO 8601 timestamp String to java.time.OffsetDateTime 如何将 Reactjs DateTimePicker 日期时间转换为 Java OffsetDateTime 或 LocalDateTime - How to convert Reactjs DateTimePicker date time convert to Java OffsetDateTime or LocalDateTime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM