2017-01-06 2 views
2

나는 게시물이 만들어 질 때 표시하기 위해 DateUtils.getRelativeTimeSpanString()을 사용하고 있습니다.시간은 전에 트위터처럼

는 반환 문자열은 같은 것입니다 : 1 분 전,하지만 난 등 (단축과 전에없이) 1m 또는 1 시간하고 싶습니다.

"시간"을 "h"또는 "분"으로 "m"으로 바꿀 수 있지만 언어가 영어와 다른 경우 작동하지 않습니다. 그것은 Twitter이 현재 사용하고있는 것입니다. 영어/키릴 문자 Twitter로 표시하는 방법.

enter image description here

enter image description here

UPDATE : 내가 여기 (다시 JodaTime 패키지를 사용) 청소기 솔루션을 추가 할 것입니다하지만 내가 @Bradley 윌슨의 대답을 받아 들일 것입니다. 또한 나머지 답변도 같은 결과로 수정 될 수 있으므로 투표권이 있습니다. 모두 감사합니다 :

Build.Gradle 파일과 같이 앱 수준으로 종속성을 추가

DateTime postMaded = new DateTime(your previous date); 
    DateTime nowUpdate = new DateTime(); 

    Period period = new Period(postMaded, nowUpdate); 

    PeriodFormatter formatter; 

    Locale current = ConverterMethods.getCurrentLocale(); 

    if (current.getLanguage().contentEquals(any Cyrillic language)) { 

     if (period.getYears() != 0) { 
      formatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" г.").printZeroNever().toFormatter(); 
     } else if (period.getMonths() != 0) { 
      formatter = new PeriodFormatterBuilder().appendMonths().appendSuffix(" м").printZeroNever().toFormatter(); 
     } else if (period.getWeeks() != 0) { 
      formatter = new PeriodFormatterBuilder().appendWeeks().appendSuffix(" седм.").printZeroNever().toFormatter(); 
     } else if (period.getDays() != 0) { 
      formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" д").printZeroNever().toFormatter(); 
     } else if (period.getHours() != 0) { 
      formatter = new PeriodFormatterBuilder().appendHours().appendSuffix(" ч").printZeroNever().toFormatter(); 
     } else if (period.getMinutes() != 0) { 
      formatter = new PeriodFormatterBuilder().appendMinutes().appendSuffix(" мин").printZeroNever().toFormatter(); 
     } else { 
      formatter = new PeriodFormatterBuilder().appendSeconds().appendSuffix(" с").printZeroNever().toFormatter(); 
     } 

    } else { 

     if (period.getYears() != 0) { 
      formatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" y").printZeroNever().toFormatter(); 
     } else if (period.getMonths() != 0) { 
      formatter = new PeriodFormatterBuilder().appendMonths().appendSuffix(" mon").printZeroNever().toFormatter(); 
     } else if (period.getWeeks() != 0) { 
      formatter = new PeriodFormatterBuilder().appendWeeks().appendSuffix(" w").printZeroNever().toFormatter(); 
     } else if (period.getDays() != 0) { 
      formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" d").printZeroNever().toFormatter(); 
     } else if (period.getHours() != 0) { 
      formatter = new PeriodFormatterBuilder().appendHours().appendSuffix(" h").printZeroNever().toFormatter(); 
     } else if (period.getMinutes() != 0) { 
      formatter = new PeriodFormatterBuilder().appendMinutes().appendSuffix(" m").printZeroNever().toFormatter(); 
     } else { 
      formatter = new PeriodFormatterBuilder().appendSeconds().appendSuffix(" s").printZeroNever().toFormatter(); 
     } 
    } 
+1

Joda-Time (https://github.com/dlew/joda-time-android)에는 그런 일을하기위한 좋은 옵션이 있습니다. –

+0

'Period','PeriodFormatter','PeriodFormatterBuilder' 클래스를 포함하는 패키지를 지정하면 도움이 될 것입니다. – RustamG

+0

추가했습니다. 그것을 지적 주셔서 감사합니다. – charbinary

답변

1

당신은 달성하기 위해 JodaTime를 사용할 수있는 수행하기 위해이 기능을 사용할 수 있습니다 :

compile 'net.danlew:android.joda:2.9.4.1' 

다음으로 간단히 구현할 수 있습니다. 이 기능.

private String time = "Just Now"; 

private String how_long_ago(String created_at) { 
     DateTime sinceGraduation = new DateTime(created_at, GregorianChronology.getInstance()); 
     DateTime currentDate = new DateTime(); //current date 

     Months diffInMonths = Months.monthsBetween(sinceGraduation, currentDate); 
     Days diffInDays = Days.daysBetween(sinceGraduation, currentDate); 
     Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate); 
     Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate); 
     Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate); 

     Log.d("since grad", "before if " + sinceGraduation); 
     if (diffInDays.isGreaterThan(Days.days(31))) { 
      time = diffInMonths.getMonths() + " months ago"; 
      if (diffInMonths.getMonths() == 1) { 
       time = diffInMonths.getMonths() + " month ago"; 
      } else { 
       time = diffInMonths.getMonths() + " months ago"; 
      } 
      return time; 
     } else if (diffInHours.isGreaterThan(Hours.hours(24))) { 
      if (diffInDays.getDays() == 1) { 
       time = diffInDays.getDays() + " day ago"; 
      } else { 
       time = diffInDays.getDays() + " days ago"; 
      } 
      return time; 
     } else if (diffInMinutes.isGreaterThan(Minutes.minutes(60))) { 
      if (diffInHours.getHours() == 1) { 
       time = diffInHours.getHours() + " hour ago"; 
      } else { 
       time = diffInHours.getHours() + " hours ago"; 
      } 
      return time; 
     } else if (seconds.isGreaterThan(Seconds.seconds(60))) { 
      if (diffInMinutes.getMinutes() == 1) { 
       time = diffInMinutes.getMinutes() + " minute ago"; 
      } else { 
       time = diffInMinutes.getMinutes() + " minutes ago"; 
      } 
      return time; 
     } else if (seconds.isLessThan(Seconds.seconds(60))) { 
      return time; 
     } 
     Log.d("since grad", "" + sinceGraduation); 
     return time; 
    } 

그냥 원하는 '1m'

을 달성하기 위해 timeString 출력을 변경 : 당신은 당신의 자원을 통해 문자열을 변경하는 현지화를 사용할 수 있습니다.

자세한 내용은 Android Localization Tutorial을 참조하십시오.

2

는이

public static String getTimeAgo(long time) { 
    if (time < 1000000000000L) { 
    // if timestamp given in seconds, convert to millis 
    time *= 1000; 
    } 

    long now = System.currentTimeMillis(); 
    if (time > now || time <= 0) { 
    return null; 
    } 

    // TODO: localize 
    final long diff = now - time; 
    if (diff < MINUTE_MILLIS) { 
    return "just now"; 
    } else if (diff < 2 * MINUTE_MILLIS) { 
    return "a minute ago"; 
    } else if (diff < 50 * MINUTE_MILLIS) { 
    return diff/MINUTE_MILLIS + " min ago"; 
    } else if (diff < 90 * MINUTE_MILLIS) { 
    return "an hour ago"; 
    } else if (diff < 24 * HOUR_MILLIS) { 
    return diff/HOUR_MILLIS + " hours ago"; 
    } else if (diff < 48 * HOUR_MILLIS) { 
    return "yesterday"; 
    } else { 
    return diff/DAY_MILLIS + " days ago"; 
    } 
} 
+1

아니요, 언어가 영어가 아닌 경우 어떤 경우에도 입력 할 수 없기 때문에 가능하지 않습니다. 예를 들어 키릴 어 분/분은 "минута/мин"입니다. – charbinary

+0

현지화에 문자열 리소스를 사용할 수 있습니다. @ionicorn –

4

PrettyTime 라이브러리를 살펴보십시오.

그것은 사용하기 매우 간단합니다

import org.ocpsoft.prettytime.PrettyTime

PrettyTime p = new PrettyTime(); 
System.out.println(p.format(new Date())); 
// prints "moments ago" 

OU는 국제화 된 메시지에 대한 로케일에 전달할 수 있습니다

코멘트에서 언급 한 바와 같이
PrettyTime p = new PrettyTime(new Locale("fr")); 
System.out.println(p.format(new Date())); 
// prints "à l'instant" 

는, 안드로이드는이 기능이 android.text.format.DateUtils 클래스에 내장되어 있습니다.당신이 당신의 질문에 지정한처럼 일하는 것이 내 라이브러리 Time4A를 사용

+0

DateUtils.getRelativeTimeSpanString()을 사용한다고 말한대로 작동합니다. 그러나 모든 언어로 출력을 사용자 정의하고 싶습니다. 이미지보기 – charbinary

+0

먼저이 라이브러리'PrettyTime'을 시도하는 두 번째 옵션입니다. –

+0

한 가지 문제 : 축약 된 스타일을 실현하는 방법이 보이지 않습니다. 예를 들어이 [resource] (https://github.com/ocpsoft/prettytime/blob/master/core/src/main/java/org)를 참조하십시오. /ocpsoft/prettytime/i18n/Resources_en.java). OP는 구성 가능한 텍스트 너비에 대한 강한 소원을 갖고있는 것처럼 보입니다. 내 답변도 참조하십시오. –

1

: (전-단어)

인쇄 상대 시간 전에 단어없이

PlainTimestamp now = PlainTimestamp.nowInSystemTime(); 
    PlainTimestamp earlier = now.minus(1, ClockUnit.MINUTES); 
    Moment past = earlier.inStdTimezone(); 
    Locale russian = new Locale("ru"); 

    PrettyTime.of(Locale.ENGLISH).printRelativeInStdTimezone(past); 
    // output: 1 minute ago 

    PrettyTime.of(Locale.ENGLISH) 
     .withShortStyle().printRelativeInStdTimezone(past); 
    // output: 1 min. ago 

    PrettyTime.of(russian).printRelativeInStdTimezone(past); 
    // output: 1 минуту назад 

    PrettyTime.of(russian).withShortStyle().printRelativeInStdTimezone(past); 
    // output: 1 мин. назад 

인쇄 평면 번

IsoUnit days = CalendarUnit.DAYS; 
    IsoUnit hours = ClockUnit.HOURS; 
    IsoUnit minutes = ClockUnit.MINUTES; 
    net.time4j.Duration<IsoUnit> d = 
     Duration.in(Timezone.ofSystem(), days, hours, minutes) 
      .between(earlier, now); 

    PrettyTime.of(Locale.ENGLISH).print(d, TextWidth.WIDE); 
    // output: 1 minute 

    PrettyTime.of(Locale.ENGLISH).print(d, TextWidth.ABBREVIATED); 
    // output: 1 min 

    PrettyTime.of(Locale.ENGLISH).print(d, TextWidth.NARROW); 
    // output: 1m 

    PrettyTime.of(russian).print(d, TextWidth.WIDE); 
    // output: 1 минута 

    PrettyTime.of(russian).print(d, TextWidth.ABBREVIATED); 
    // output: 1 мин 

    PrettyTime.of(russian).print(d, TextWidth.NARROW); 
    // output: 1 мин 

최신 라이브러리 버전은 CLDR 저장소 v30.0.2의 데이터 (유니 코드 컨소시엄에서, 실제로 80 개 언어로). 필요한 경우 Time4A와 함께 배포 할 자체 자산을 정의한 다음 (기본 자산을 재정의) 텍스트 자원을 변경하고자 할 수 있습니다.