时差计划

时间:2013-03-21 06:24:16

标签: java datetime

我正在使用以下功能来计算时差。它没有显示正确的输出。在1个月的时间差后,它显示出2分钟的差异。

我的计划有什么问题?

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

3 个答案:

答案 0 :(得分:9)

我建议您查看Joda Time,注意:

  

Joda-Time是Java SE 8之前Java的事实标准日期和时间库。现在要求用户迁移到java.time(JSR-310)。

安装

  • 对于基于Debian的系统:libjoda-time-java。该jar将位于/usr/share/java joda-time.jar
  • 对于其他人:Download最新的jar,例如: joda-time-2.2-dist.zip,其中包括joda-time-2.2.jar

使用Eclipse时,将其添加到Java Build路径(Project> Properties> Java Build Path> Add External Jar)

相关JavaDoc

示例代码

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

输出:

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

为什么我推荐一种新的解决方案

  • 它更短(与1665个字符/ 41行相比,726个字符/ 14行)
  • 更容易理解
  • 更容易调整
  • 代码和演示文稿的分离更加清晰
  • 我不想修复你的代码

答案 1 :(得分:2)

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


}

答案 2 :(得分:-1)

不要将long投射到int,因为它会失去精确度。 将所有int更改为long,然后查看差异。

希望这个帮助