【问题标题】:How to get time stamp based on date(getting timestamp for the time of that particular date )如何根据日期获取时间戳(获取该特定日期时间的时间戳)
【发布时间】:2015-03-10 10:42:47
【问题描述】:

请解决我的问题

我正在获取日期 16-03-2015 23:05 的时间戳 也适用于 17-03-2015 00:10

我通过传递 17-03-2015 00:10 时间戳作为参数在 16-03-2015 23:05 调用 after() 方法

我的问题是时间戳只考虑时间

所以在这种情况下 23:05 的时间戳大于 00:10

但是当我们比较日期 17-03-2015 00:10 早于 16-03-2015 23:05

我想根据日期获取时间戳有什么方法可以找到 请帮忙

【问题讨论】:

  • 你到底想要什么? 17-03-2015 00:10 不能早于 16-03-2015 23:05,除非您使用不同的日历。
  • 一定是你这边的日期转换bug。 new java.sql.Timestamp(new SimpleDateFormat("dd-MM-yyyy HH:mm").parse("....").getTime())
  • 你想只比较日期的时间部分吗?

标签: java timestamp


【解决方案1】:

您使用什么时间戳类?当我尝试使用 java.sql.Timestamp 重现您的案例时,一切正常:

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

public class TimestampProblem {

    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        long now = c.getTimeInMillis();
        Timestamp t = new Timestamp(now);
        // add only 23 hours in order to have less hours at next day
        c.add(Calendar.HOUR, 23);
        long later = c.getTimeInMillis();
        Timestamp t2 = new Timestamp(later);
        System.out.println(t2);

        System.out.println(t.before(t2) ? "alright: <" + t + "> before <" + t2
                + ">" : "Bäm");

        Date d = new Date(now);
        Date d2 = new Date(later);

        System.out.println(d.before(d2) ? "alright: <" + d + "> before <" + d2
                + ">" : "Bäm");
    }

}

输出:

Timestamp comparison alright: <2015-03-10 12:01:47.061> before <2015-03-11 11:01:47.061>
Date comparison alright: <Tue Mar 10 12:01:47 CET 2015> before <Wed Mar 11 11:01:47 CET 2015>

也许你可以添加一个code-sn-p。

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 2014-05-22
    • 2013-03-10
    • 2023-03-22
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多