Skip to content

Instantly share code, notes, and snippets.

@dzwillpower
Forked from yava555/RelativeTime.java
Last active December 19, 2015 13:39
Show Gist options
  • Save dzwillpower/5963848 to your computer and use it in GitHub Desktop.
Save dzwillpower/5963848 to your computer and use it in GitHub Desktop.
#SimpleDateFormat #时间转换 将时间戳转化为指定格式的时间
package com.xianguo.xreader.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
public class RelativeTime {
private static final long ONE_DAY = 86400000L;
private static final long ONE_HOUR = 3600000L;
private static final long ONE_MINUTE = 60000L;
@SuppressLint("SimpleDateFormat") private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
public static String format(long milliseconds) {
long l = new Date().getTime() - milliseconds;
String str;
if (l < ONE_MINUTE) {
str = "刚刚";
} else if (l < ONE_HOUR) {
str = toMinutes(l) + " 分钟前";
} else if (l < ONE_DAY) {
str = toHours(l) + " 小时前";
} else if (toDays(l) == 1L) {
str = "昨天";
} else {
str = simpleDateFormat.format(milliseconds);
}
return str;
}
private static long toDays(long milliseconds) {
return toHours(milliseconds) / 24L;
}
private static long toHours(long milliseconds) {
return toMinutes(milliseconds) / 60L;
}
private static long toMinutes(long milliseconds) {
return toSeconds(milliseconds) / 60L;
}
private static long toSeconds(long milliseconds) {
return milliseconds / 1000L;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment