【问题标题】:JAVA new Timestamp() make ending ZERO disappear when time in ms end with ZEROJAVA new Timestamp() 使结束零在毫秒时间以零结束时消失
【发布时间】:2017-04-05 09:43:10
【问题描述】:

在我的日志中我使用的是:(java.sql.Timestamp)

 new Timestamp(System.currentTimeMillis())

它的行为很奇怪(恕我直言):

  • 当 System.currentTimeMillis() = 1490713735960

    返回:2017-03-28 17:08:55.96

我预计会有:2017-03-28 17:08:55.960,结尾是 0

  • 当 System.currentTimeMillis() = 1490713724721

    返回:2017-03-28 17:08:44.721

    如预期的那样

问题:

这是 new Timestamp() 的正常行为吗?

为什么要删除终止的零?

【问题讨论】:

  • 我想java.sql.Timestamp 对吧?
  • 是:java.sql.Timestamp

标签: java timestamp


【解决方案1】:

所以,是的,这是正确的行为。因为toString()方法对于纳秒部分的实现是:

if (nanos == 0) {
    nanosString = "0";
} else {
    nanosString = Integer.toString(nanos);
    ...
}

else 部分:

// Truncate trailing zeros
char[] nanosChar = new char[nanosString.length()];
nanosString.getChars(0, nanosString.length(), nanosChar, 0);
int truncIndex = 8;
while (nanosChar[truncIndex] == '0') {
    truncIndex--;
}

nanosString = new String(nanosChar, 0, truncIndex + 1);

看看java.sql.Timestamp.toString()方法的源码

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2015-06-25
    • 1970-01-01
    相关资源
    最近更新 更多