import java.text.SimpleDateFormat;
public class test {
public static void main(String[] args){
String str = formatTime(1435484260);
System.out.println(str);
}
public static String formatTime(long time){
time = time * 1000;
SimpleDateFormat hms = new SimpleDateFormat("HH:mm:ss");
long currTime = System.currentTimeMillis();
long todayTime = currTime - currTime%(24*60*60*1000); // 今天0点
long nGap = todayTime - time; // 距今天0点的毫秒数
String result = "";
if(nGap <= 0){ // 今天
result = hms.format(time);
}else if( nGap < 24*60*60*1000 ){ // 昨天
result = "昨天" + hms.format(time);
}else if( nGap > 365*24*60*60*1000 ){ // 不是今年
SimpleDateFormat ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result = ymdhms.format(time);
}else{
SimpleDateFormat mdhms = new SimpleDateFormat("MM-dd HH:mm:ss");
result = mdhms.format(time);
}
return result;
}
}
本文介绍了一个Java程序,该程序能够根据输入的时间戳返回不同格式的时间字符串。具体来说,如果时间戳对应今天的时间,则返回HH:mm:ss格式;如果是昨天,则在前面加上“昨天”二字;若属于当年但非今天或昨天,则采用MM-dd HH:mm:ss格式;若不属于当年,则使用完整日期格式即yyyy-MM-dd HH:mm:ss。
876

被折叠的 条评论
为什么被折叠?



