如何在Java中计算时间跨度并设置输出格式?

2022-09-01 00:15:20

我想取两次(自epoch以来的几秒钟),并以如下格式显示两者之间的差异:

  • 2 分钟
  • 1 小时 15 分钟
  • 3 小时, 9 分钟
  • 1分钟前
  • 1 小时, 2 分钟 前

我该如何做到这一点?


答案 1

由于每个人都大喊“YOODAA!!!”,但没有人发布具体的例子,这是我的贡献。

你也可以用Joda-Time做到这一点。使用“期间”表示一个期间。要以所需的人工表示形式格式化周期,请使用可以通过CiementFormatterBuilder构建的CiementFormatter

下面是一个启动示例:

DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendYears().appendSuffix(" year, ", " years, ")
    .appendMonths().appendSuffix(" month, ", " months, ")
    .appendWeeks().appendSuffix(" week, ", " weeks, ")
    .appendDays().appendSuffix(" day, ", " days, ")
    .appendHours().appendSuffix(" hour, ", " hours, ")
    .appendMinutes().appendSuffix(" minute, ", " minutes, ")
    .appendSeconds().appendSuffix(" second", " seconds")
    .printZeroNever()
    .toFormatter();

String elapsed = formatter.print(period);
System.out.println(elapsed + " ago");

更加清晰和简洁,不是吗?

现在打印

32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago

(咳嗽,老,咳嗽)


答案 2
    Date start = new Date(1167627600000L); // JANUARY_1_2007
    Date end = new Date(1175400000000L); // APRIL_1_2007


    long diffInSeconds = (end.getTime() - start.getTime()) / 1000;

    long diff[] = new long[] { 0, 0, 0, 0 };
    /* sec */diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
    /* min */diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
    /* hours */diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
    /* days */diff[0] = (diffInSeconds = (diffInSeconds / 24));

    System.out.println(String.format(
        "%d day%s, %d hour%s, %d minute%s, %d second%s ago",
        diff[0],
        diff[0] > 1 ? "s" : "",
        diff[1],
        diff[1] > 1 ? "s" : "",
        diff[2],
        diff[2] > 1 ? "s" : "",
        diff[3],
        diff[3] > 1 ? "s" : ""));