Time difference program

2020-05-10 09:19发布

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.

What is wrong with my program?

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;
}

标签: java datetime
3条回答
▲ chillily
2楼-- · 2020-05-10 09:57

Don't cast long to int, cause it will lose its precision. change all int to long, and see the difference.

hope this help

查看更多
狗以群分
3楼-- · 2020-05-10 10:02
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);


}
查看更多
Emotional °昔
4楼-- · 2020-05-10 10:02

I recommend to take a look at Joda Time, noting that:

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Installation

  • For Debian-based systems: libjoda-time-java. The jar will be in /usr/share/java as joda-time.jar
  • For others: Download latest jar, e.g. joda-time-2.2-dist.zip which includes joda-time-2.2.jar

When you use Eclipse, add it to your Java Build path (Project > Properties > Java Build Path > Add External Jar)

Relevant JavaDoc

Example code

import java.sql.Timestamp;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class MinimalWorkingExample {
    static Date date = new Date(1990, 4, 28, 12, 59);

    public static String getTimestampDiff(Timestamp t) {
        final DateTime start = new DateTime(date.getTime());
        final DateTime end = new DateTime(t);
        Period p = new Period(start, end);
        PeriodFormatter formatter = new PeriodFormatterBuilder()
                .printZeroAlways().minimumPrintedDigits(2).appendYears()
                .appendSuffix(" year", " years").appendSeparator(", ")
                .appendMonths().appendSuffix(" month", " months")
                .appendSeparator(", ").appendDays()
                .appendSuffix(" day", " days").appendSeparator(" and ")
                .appendHours().appendLiteral(":").appendMinutes()
                .appendLiteral(":").appendSeconds().toFormatter();
        return p.toString(formatter);
    }

    public static void main(String[] args) {
        String diff = getTimestampDiff(new Timestamp(2013, 3, 20, 7, 51, 0, 0));
        System.out.println(diff);
    }
}

Output:

22 years, 10 months, 01 day and 18:52:00

Why I recommend a new solution

  • It is shorter (726 characters / 14 lines in comparison to your 1665 characters / 41 lines)
  • It is easier to understand
  • It is easier to adjust
  • Separation of code and presentation is clearer
  • I don't want to fix your code
查看更多
登录 后发表回答