java - 比较两个时间戳

标签 java timestamp compare

我想比较以下两个时间戳。它应该返回 true,但由于两个时间戳中存在单位数和两位数毫秒,它返回 false。我该怎么做才能让它返回 true

public static void main(String[] args) throws ParseException {
    String d1 = "2011-12-31 07:11:01.5";
    String d2 = "2011-12-31 07:11:01.50";
    SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");

    Date dateOne = s1.parse(d1);
    Date dateTwo = s2.parse(d2);

    System.out.println(dateOne.equals(dateTwo));
}

最佳答案

其他人已经回答了原因。这是解决这个问题的起点:

import java.text.*;
import java.util.Date;

public class DatePercentage {

    private final SimpleDateFormat dateFmt = new SimpleDateFormat(
                                "yyyy-MM-dd HH:mm:ss");
    private final DecimalFormat decFmt = new DecimalFormat();

    public Date parse(String text) throws ParseException {
        ParsePosition pos = new ParsePosition(0);
        Date d = dateFmt.parse(text, pos);

        if (d == null) {
            throw new ParseException("Could not parse " + text + ": " + pos,
                                     pos.getErrorIndex());
        } else if (pos.getIndex() < text.length()) {
            Number dec = decFmt.parse(text, pos); // % milliseceonds
            double pct = dec == null ? 0 : dec.doubleValue();

            if (0 < pct && pct < 1) {
                long moreMillis = Math.round(pct * 1000);
                d = new Date(d.getTime() + moreMillis);
            }
        }
        return d;
    }

    public static void main(String[] args) throws ParseException {
        String date = "2011-12-31 07:11:01";
        String [] millis = {"", ".5", ".50", ".500", ".5001", 
                            ".051", ".5009", "garbage"};

        DatePercentage dp = new DatePercentage();

        for (int i = 0; i < millis.length; i++) {
            String str = date + millis[i];
            System.out.format("%2s: %26s -> %tQ%n", i+1, str, dp.parse(str));
        }
    }
}

输出:

 1:        2011-12-31 07:11:01 -> 1325333461000
 2:      2011-12-31 07:11:01.5 -> 1325333461500
 3:     2011-12-31 07:11:01.50 -> 1325333461500
 4:    2011-12-31 07:11:01.500 -> 1325333461500
 5:   2011-12-31 07:11:01.5001 -> 1325333461500
 6:    2011-12-31 07:11:01.051 -> 1325333461051
 7:   2011-12-31 07:11:01.5009 -> 1325333461501
 8: 2011-12-31 07:11:01garbage -> 1325333461000

关于java - 比较两个时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8769456/

相关文章:

java - 将 ECPublicKey 从 JavaCard 恢复到 Java

java - J对话框标题栏图标改变

php - MySQL Laravel ORM 中的日期

java - 比较两个语句与一个定义变量java

python - 评估时间序列之间的同步性

java - 如何使这个 "cleaner"

java - 如何覆盖android中的操作栏后退按钮?

php - 当日期刚刚保存为 UNIX 时间戳时,针对特定日期的 MySQL 过滤器

mysql - 使用相同的值更新 mysql 表并仍然获得时间戳更新

c++ - 我应该为 map 中的两个智能指针对制作自己的比较器吗?