Program Tip

Joda-Time으로 지금부터 경과 시간을 계산하는 방법은 무엇입니까?

programtip 2020. 11. 7. 10:26
반응형

Joda-Time으로 지금부터 경과 시간을 계산하는 방법은 무엇입니까?


특정 날짜부터 지금까지의 경과 시간 을 계산하고 StackOverflow 질문과 동일한 형식으로 표시해야합니다.

15s ago
2min ago
2hours ago
2days ago
25th Dec 08

Java Joda-Time 라이브러리로 이를 달성하는 방법을 알고 있습니까? 이미 구현 한 도우미 메서드가 있습니까, 아니면 알고리즘을 직접 작성해야합니까?


JodaTime으로 경과 시간을 계산하려면을 사용하십시오 Period. 원하는 인간의 표현, 사용 경과 시간 포맷을 지정하려면, PeriodFormatter당신은에 의해 구축 할 수 있습니다 PeriodFormatterBuilder.

다음은 킥오프 예입니다.

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()
    .appendSeconds().appendSuffix(" seconds ago\n")
    .appendMinutes().appendSuffix(" minutes ago\n")
    .appendHours().appendSuffix(" hours ago\n")
    .appendDays().appendSuffix(" days ago\n")
    .appendWeeks().appendSuffix(" weeks ago\n")
    .appendMonths().appendSuffix(" months ago\n")
    .appendYears().appendSuffix(" years ago\n")
    .printZeroNever()
    .toFormatter();

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

이것은 지금까지 인쇄됩니다

3 초 전
51 분 전
7 시간 전
6 일 전
10 개월 전
31 년 전

(기침, 늙음, 기침) 내가 몇 달과 몇 년을 고려하여 0 일 때 값을 생략하도록 구성했음을 알 수 있습니다.


단순 경과 시간 에는 PrettyTime사용하십시오 .

@sfussenegger가 대답하고 JodaTime을 사용하여 HumanTime시도했지만 Period사람이 읽을 수있는 경과 시간에 대한 가장 쉽고 깨끗한 방법은 PrettyTime 라이브러리였습니다.

다음은 입력 및 출력에 대한 몇 가지 간단한 예입니다.

오분 전

DateTime fiveMinutesAgo = DateTime.now().minusMinutes( 5 );

new PrettyTime().format( fiveMinutesAgo.toDate() );

// Outputs: "5 minutes ago"

얼마 전에

DateTime birthday = new DateTime(1978, 3, 26, 12, 35, 0, 0);

new PrettyTime().format( birthday.toDate() );

// Outputs: "4 decades ago"

주의 : 라이브러리의 더 정확한 기능을 사용해 보았지만 이상한 결과가 나오므로주의하여 생명을 위협하지 않는 프로젝트에 사용하십시오.

JP


You can do this with a PeriodFormatter but you don't have to go to the effort of making your own PeriodFormatBuilder as in other answers. If it suits your case, you can just use the default formatter:

Period period = new Period(startDate, endDate);
System.out.println(PeriodFormat.getDefault().print(period))

(hat tip to this answer on a similar question, I'm cross-posting for discoverability)


There is a small helper class called HumanTime that I'm pretty happy with.

참고URL : https://stackoverflow.com/questions/2179644/how-to-calculate-elapsed-time-from-now-with-joda-time

반응형