本文介绍了时差程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下函数来计算时差。它没有显示正确的输出。 1个月时间差异显示2分钟差异。
I am using following function to calculate time difference. It is not showing proper output. After 1 month time difference it is showing 2 minutes difference.
我的程序有什么问题?
public String TimestampDiff(Timestamp t) {
long t1 = t.getTime();
String st = null;
long diff;
java.util.Date date = new java.util.Date();
long currT = date.getTime();
System.out.println();
System.out.println(" current timesstamp is " + currT);
diff = (currT - t1) / 60;
int years = (int) Math.floor(diff / (1000 * 60 * 60 * 24 * 365));
double remainder = Math.floor(diff % (1000 * 60 * 60 * 24 * 365));
int days = (int) Math.floor(remainder / (1000 * 60 * 60 * 24));
remainder = Math.floor(remainder % (1000 * 60 * 60 * 24));
int hours = (int) Math.floor(remainder / (1000 * 60 * 60));
remainder = Math.floor(remainder % (1000 * 60 * 60));
int minutes = (int) Math.floor(remainder / (1000 * 60));
remainder = Math.floor(remainder % (1000 * 60));
int seconds = (int) Math.floor(remainder / (1000));
System.out.println("\nyr:Ds:hh:mm:ss " + years + ":" + days + ":"
+ hours + ":" + minutes + ":" + seconds);
if (years == 0 && days == 0 && hours == 0 && minutes == 0) {
st = "few seconds ago";
} else if (years == 0 && days == 0 && hours == 0) {
st = minutes + " minuts ago";
} else if (years == 0 && days == 0) {
st = hours + " hours ago";
} else if (years == 0 && days == 1) {
st = new SimpleDateFormat("'yesterday at' hh:mm a").format(t1);
} else if (years == 0 && days > 1) {
st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(t1);
} else if (years > 0) {
st = new SimpleDateFormat("MMM d ''yy 'at' hh:mm a").format(t1);
}
st = st.replace("AM", "am").replace("PM", "pm");
return st;
}
推荐答案
import org.apache.commons.lang.time.DateUtils;
import java.text.SimpleDateFormat;
@Test
public void testDate() throws Exception {
long t1 = new SimpleDateFormat("dd.MM.yyyy").parse("20.03.2013").getTime();
long now = System.currentTimeMillis();
String result = null;
long diff = Math.abs(t1-now);
if(diff < DateUtils.MILLIS_PER_MINUTE){
result = "few seconds ago";
}else if(diff < DateUtils.MILLIS_PER_HOUR){
result = (int)(diff/DateUtils.MILLIS_PER_MINUTE) + " minuts ago";
}else if(diff < DateUtils.MILLIS_PER_DAY){
result = (int)(diff/DateUtils.MILLIS_PER_HOUR) + " hours ago";
}else if(diff < DateUtils.MILLIS_PER_DAY * 2){
result = new SimpleDateFormat("'yesterday at' hh:mm a").format(t1);
}else if(diff < DateUtils.MILLIS_PER_DAY * 365){
result = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(t1);
} else{
result = new SimpleDateFormat("MMM d ''yy 'at' hh:mm a").format(t1);
}
result = result.replace("AM", "am").replace("PM", "pm");
System.out.println(result);
}
这篇关于时差程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!