Ruby on Railsには、任意の日付を取得して、それが「どれくらい前」であったかを印刷できる機能があります。
例えば:
8 minutes ago
8 hours ago
8 days ago
8 months ago
8 years ago
Javaでこれを行う簡単な方法はありますか?
Ruby on Railsには、任意の日付を取得して、それが「どれくらい前」であったかを印刷できる機能があります。
例えば:
8 minutes ago
8 hours ago
8 days ago
8 months ago
8 years ago
Javaでこれを行う簡単な方法はありますか?
PrettyTimeライブラリを見てください。
使い方はとても簡単です:
import org.ocpsoft.prettytime.PrettyTime;
PrettyTime p = new PrettyTime();
System.out.println(p.format(new Date()));
// prints "moments ago"
国際化されたメッセージのロケールを渡すこともできます。
PrettyTime p = new PrettyTime(new Locale("fr"));
System.out.println(p.format(new Date()));
// prints "à l'instant"
android.text.format.DateUtils
コメントで述べたように、Android にはこの機能がクラスに組み込まれています。
TimeUnit列挙型を検討しましたか?このようなことにはかなり便利です
try {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date past = format.parse("01/10/2010");
Date now = new Date();
System.out.println(TimeUnit.MILLISECONDS.toMillis(now.getTime() - past.getTime()) + " milliseconds ago");
System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");
}
catch (Exception j){
j.printStackTrace();
}
RealHowTo と Ben J の回答を参考にして、独自のバージョンを作成します。
public class TimeAgo {
public static final List<Long> times = Arrays.asList(
TimeUnit.DAYS.toMillis(365),
TimeUnit.DAYS.toMillis(30),
TimeUnit.DAYS.toMillis(1),
TimeUnit.HOURS.toMillis(1),
TimeUnit.MINUTES.toMillis(1),
TimeUnit.SECONDS.toMillis(1) );
public static final List<String> timesString = Arrays.asList("year","month","day","hour","minute","second");
public static String toDuration(long duration) {
StringBuffer res = new StringBuffer();
for(int i=0;i< TimeAgo.times.size(); i++) {
Long current = TimeAgo.times.get(i);
long temp = duration/current;
if(temp>0) {
res.append(temp).append(" ").append( TimeAgo.timesString.get(i) ).append(temp != 1 ? "s" : "").append(" ago");
break;
}
}
if("".equals(res.toString()))
return "0 seconds ago";
else
return res.toString();
}
public static void main(String args[]) {
System.out.println(toDuration(123));
System.out.println(toDuration(1230));
System.out.println(toDuration(12300));
System.out.println(toDuration(123000));
System.out.println(toDuration(1230000));
System.out.println(toDuration(12300000));
System.out.println(toDuration(123000000));
System.out.println(toDuration(1230000000));
System.out.println(toDuration(12300000000L));
System.out.println(toDuration(123000000000L));
}}
以下を出力します
0 second ago
1 second ago
12 seconds ago
2 minutes ago
20 minutes ago
3 hours ago
1 day ago
14 days ago
4 months ago
3 years ago
public class TimeUtils {
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static void main(String args[]) {
System.out.println(millisToLongDHMS(123));
System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
}
}
これは RealHowTo の回答に基づいているため、気に入ったら、彼/彼女にも愛を与えてください。
このクリーンアップされたバージョンでは、関心のある時間の範囲を指定できます。
また、" と " の部分の処理も少し異なります。文字列を区切り記号で結合するとき、複雑なロジックをスキップして、完了したら最後の区切り記号を削除する方が簡単なことがよくあります。
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class TimeUtils {
/**
* Converts time to a human readable format within the specified range
*
* @param duration the time in milliseconds to be converted
* @param max the highest time unit of interest
* @param min the lowest time unit of interest
*/
public static String formatMillis(long duration, TimeUnit max, TimeUnit min) {
StringBuilder res = new StringBuilder();
TimeUnit current = max;
while (duration > 0) {
long temp = current.convert(duration, MILLISECONDS);
if (temp > 0) {
duration -= current.toMillis(temp);
res.append(temp).append(" ").append(current.name().toLowerCase());
if (temp < 2) res.deleteCharAt(res.length() - 1);
res.append(", ");
}
if (current == min) break;
current = TimeUnit.values()[current.ordinal() - 1];
}
// clean up our formatting....
// we never got a hit, the time is lower than we care about
if (res.lastIndexOf(", ") < 0) return "0 " + min.name().toLowerCase();
// yank trailing ", "
res.deleteCharAt(res.length() - 2);
// convert last ", " to " and"
int i = res.lastIndexOf(", ");
if (i > 0) {
res.deleteCharAt(i);
res.insert(i, " and");
}
return res.toString();
}
}
回転させるための小さなコード:
import static java.util.concurrent.TimeUnit.*;
public class Main {
public static void main(String args[]) {
long[] durations = new long[]{
123,
SECONDS.toMillis(5) + 123,
DAYS.toMillis(1) + HOURS.toMillis(1),
DAYS.toMillis(1) + SECONDS.toMillis(2),
DAYS.toMillis(1) + HOURS.toMillis(1) + MINUTES.toMillis(2),
DAYS.toMillis(4) + HOURS.toMillis(3) + MINUTES.toMillis(2) + SECONDS.toMillis(1),
DAYS.toMillis(5) + HOURS.toMillis(4) + MINUTES.toMillis(1) + SECONDS.toMillis(23) + 123,
DAYS.toMillis(42)
};
for (long duration : durations) {
System.out.println(TimeUtils.formatMillis(duration, DAYS, SECONDS));
}
System.out.println("\nAgain in only hours and minutes\n");
for (long duration : durations) {
System.out.println(TimeUtils.formatMillis(duration, HOURS, MINUTES));
}
}
}
次のように出力されます。
0 seconds
5 seconds
1 day and 1 hour
1 day and 2 seconds
1 day, 1 hour and 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
Again in only hours and minutes
0 minutes
0 minutes
25 hours
24 hours
25 hours and 2 minutes
99 hours and 2 minutes
124 hours and 1 minute
1008 hours
そして、誰かがそれを必要とする場合に備えて、上記のような文字列をミリ秒に変換するクラスを次に示します。人々が読みやすいテキストでさまざまなことのタイムアウトを指定できるようにするのに非常に便利です。
これを行う簡単な方法があります。
20分前の時間が欲しいとしましょう:
Long minutesAgo = new Long(20);
Date date = new Date();
Date dateIn_X_MinAgo = new Date (date.getTime() - minutesAgo*60*1000);
それでおしまい..
ここでの一連の回答に基づいて、ユースケース用に以下を作成しました。
使用例:
String relativeDate = String.valueOf(
TimeUtils.getRelativeTime( 1000L * myTimeInMillis() ));
import java.util.Arrays;
import java.util.List;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Utilities for dealing with dates and times
*/
public class TimeUtils {
public static final List<Long> times = Arrays.asList(
DAYS.toMillis(365),
DAYS.toMillis(30),
DAYS.toMillis(7),
DAYS.toMillis(1),
HOURS.toMillis(1),
MINUTES.toMillis(1),
SECONDS.toMillis(1)
);
public static final List<String> timesString = Arrays.asList(
"yr", "mo", "wk", "day", "hr", "min", "sec"
);
/**
* Get relative time ago for date
*
* NOTE:
* if (duration > WEEK_IN_MILLIS) getRelativeTimeSpanString prints the date.
*
* ALT:
* return getRelativeTimeSpanString(date, now, SECOND_IN_MILLIS, FORMAT_ABBREV_RELATIVE);
*
* @param date String.valueOf(TimeUtils.getRelativeTime(1000L * Date/Time in Millis)
* @return relative time
*/
public static CharSequence getRelativeTime(final long date) {
return toDuration( Math.abs(System.currentTimeMillis() - date) );
}
private static String toDuration(long duration) {
StringBuilder sb = new StringBuilder();
for(int i=0;i< times.size(); i++) {
Long current = times.get(i);
long temp = duration / current;
if (temp > 0) {
sb.append(temp)
.append(" ")
.append(timesString.get(i))
.append(temp > 1 ? "s" : "")
.append(" ago");
break;
}
}
return sb.toString().isEmpty() ? "now" : sb.toString();
}
}
シンプルな「今日」、「昨日」、または「x 日前」を探している場合。
private String getDaysAgo(Date date){
long days = (new Date().getTime() - date.getTime()) / 86400000;
if(days == 0) return "Today";
else if(days == 1) return "Yesterday";
else return days + " days ago";
}
Java 8 以降に組み込まれているjava.timeフレームワークを使用します。
LocalDateTime t1 = LocalDateTime.of(2015, 1, 1, 0, 0, 0);
LocalDateTime t2 = LocalDateTime.now();
Period period = Period.between(t1.toLocalDate(), t2.toLocalDate());
Duration duration = Duration.between(t1, t2);
System.out.println("First January 2015 is " + period.getYears() + " years ago");
System.out.println("First January 2015 is " + period.getMonths() + " months ago");
System.out.println("First January 2015 is " + period.getDays() + " days ago");
System.out.println("First January 2015 is " + duration.toHours() + " hours ago");
System.out.println("First January 2015 is " + duration.toMinutes() + " minutes ago");
私はあなたが求めていることを行うjquery-timeagoプラグインの単純なJavatimeagoポートを作成しました。
TimeAgo time = new TimeAgo();
String minutes = time.timeAgo(System.currentTimeMillis() - (15*60*1000)); // returns "15 minutes ago"
この関数を使用して、過去の時間を計算できます
private String timeAgo(long time_ago) {
long cur_time = (Calendar.getInstance().getTimeInMillis()) / 1000;
long time_elapsed = cur_time - time_ago;
long seconds = time_elapsed;
int minutes = Math.round(time_elapsed / 60);
int hours = Math.round(time_elapsed / 3600);
int days = Math.round(time_elapsed / 86400);
int weeks = Math.round(time_elapsed / 604800);
int months = Math.round(time_elapsed / 2600640);
int years = Math.round(time_elapsed / 31207680);
// Seconds
if (seconds <= 60) {
return "just now";
}
//Minutes
else if (minutes <= 60) {
if (minutes == 1) {
return "one minute ago";
} else {
return minutes + " minutes ago";
}
}
//Hours
else if (hours <= 24) {
if (hours == 1) {
return "an hour ago";
} else {
return hours + " hrs ago";
}
}
//Days
else if (days <= 7) {
if (days == 1) {
return "yesterday";
} else {
return days + " days ago";
}
}
//Weeks
else if (weeks <= 4.3) {
if (weeks == 1) {
return "a week ago";
} else {
return weeks + " weeks ago";
}
}
//Months
else if (months <= 12) {
if (months == 1) {
return "a month ago";
} else {
return months + " months ago";
}
}
//Years
else {
if (years == 1) {
return "one year ago";
} else {
return years + " years ago";
}
}
}
1) ここで time_ago はマイクロ秒単位です
Android 用のアプリを開発している場合は、そのようなすべての要件に対応するユーティリティ クラスDateUtilsが提供されます。DateUtils#getRelativeTimeSpanString()ユーティリティ メソッドを見てください。
のドキュメントから
CharSequence getRelativeTimeSpanString (長い時間、長い現在、長い minResolution)
「時間」を「現在」に対する相対的な時間として表す文字列を返します。過去の期間は、「42 分前」のようにフォーマットされます。将来の期間は、「42 分後」のようにフォーマットされます。
あなたは今と同じようにあなたtimestamp
の時間を過ごします。では、レポートする最小期間を指定できます。System.currentTimeMillis()
minResolution
たとえば、これが MINUTE_IN_MILLIS に設定されている場合、過去 3 秒の時間は「0 分前」として報告されます。0、MINUTE_IN_MILLIS、HOUR_IN_MILLIS、DAY_IN_MILLIS、WEEK_IN_MILLIS などのいずれかを渡します。
それはきれいではありません...しかし、私が考えることができる最も近いのはJoda-Timeを使用することです(この投稿で説明されているように: Joda Timeで今から経過時間を計算する方法?
長い研究の後、私はこれを見つけました。
public class GetTimeLapse {
public static String getlongtoago(long createdAt) {
DateFormat userDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat dateFormatNeeded = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS");
Date date = null;
date = new Date(createdAt);
String crdate1 = dateFormatNeeded.format(date);
// Date Calculation
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
crdate1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(date);
// get current date time with Calendar()
Calendar cal = Calendar.getInstance();
String currenttime = dateFormat.format(cal.getTime());
Date CreatedAt = null;
Date current = null;
try {
CreatedAt = dateFormat.parse(crdate1);
current = dateFormat.parse(currenttime);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = current.getTime() - CreatedAt.getTime();
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
String time = null;
if (diffDays > 0) {
if (diffDays == 1) {
time = diffDays + "day ago ";
} else {
time = diffDays + "days ago ";
}
} else {
if (diffHours > 0) {
if (diffHours == 1) {
time = diffHours + "hr ago";
} else {
time = diffHours + "hrs ago";
}
} else {
if (diffMinutes > 0) {
if (diffMinutes == 1) {
time = diffMinutes + "min ago";
} else {
time = diffMinutes + "mins ago";
}
} else {
if (diffSeconds > 0) {
time = diffSeconds + "secs ago";
}
}
}
}
return time;
}
}
Android の場合 Ravi が言ったとおりですが、多くの人が単にコピペしたいので、ここに貼り付けます。
try {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
Date dt = formatter.parse(date_from_server);
CharSequence output = DateUtils.getRelativeTimeSpanString (dt.getTime());
your_textview.setText(output.toString());
} catch (Exception ex) {
ex.printStackTrace();
your_textview.setText("");
}
お時間のある方への説明
元。Wed, 27 Jan 2016 09:32:35 GMT の形式でサーバーからデータを取得します [これはおそらくあなたの場合ではありません]
これは翻訳されます
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
どうすればそれを知ることができますか? こちらのドキュメントをお読みください。
次に、それを解析した後、日付を取得します。その日付を getRelativeTimeSpanString に入れました (追加のパラメーターがなくても問題ありません。デフォルトは分です)
正しい解析文字列がわからない場合は、文字 5の例外のような例外が発生します。文字 5 を見て、最初の解析文字列を修正します。. 別の例外が発生する場合があります。正しい数式が得られるまで、これらの手順を繰り返します。