Skip to content

Instantly share code, notes, and snippets.

@MaySnow
Created August 6, 2012 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaySnow/3274670 to your computer and use it in GitHub Desktop.
Save MaySnow/3274670 to your computer and use it in GitHub Desktop.
Java中时间间隔的计算(以前的时间与现在的时间间隔)
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class IntervalUtil {
public String getInterval(String createtime) {
String interval = null;
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date d1 = (Date) sd.parse(createtime, pos);
long time = new Date().getTime() - d1.getTime();
if(time/1000 < 10 && time/1000 > 0) {
interval ="刚刚";
} else if(time/3600000 < 24 && time/3600000 > 0) {
int h = (int) (time/3600000);
interval = h + "小时前";
} else if(time/60000 < 60 && time/60000 > 0) {
int m = (int) ((time%3600000)/60000);
interval = m + "分钟前";
} else if(time/1000 < 60 && time/1000 > 0) {
int se = (int) ((time%60000)/1000);
interval = se + "秒前";
}else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
ParsePosition pos2 = new ParsePosition(0);
Date d2 = (Date) sdf.parse(createtime, pos2);
interval = sdf.format(d2);
}
return interval;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment