相关疑难解决方法(0)

java.util.Date格式SSSSSS:如果不是微秒,那么最后3位是什么?

刚刚在我的Windows(8)工作站和AIX上测试了这段代码:

    public static void main(String[] args) {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(new Date()));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(new Date()));
    }
Run Code Online (Sandbox Code Playgroud)

并得到类似的结果:

2013-10-07 12:53:26.000905
2013-10-07 12:53:26.000906
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下,如果不是微秒,最后的数字是什么?

注意:我与DB2数据库交互,其中使用定时列作为TIMESTAMP存储按时间顺序排列的数据,其中6位数字在秒之后,即微秒(IMO).但是所有这些"时间戳"都是通过请求以下查询来创建的:

SELECT current timestamp as currenttimestamp FROM Table ( values (1)) temp
Run Code Online (Sandbox Code Playgroud)

我想知道,鉴于上述结果,我不能只使用我的代码new Date()而不是current timestamp从数据库中选择.

谢谢.

PS:我搜索但发现没有相关(已回答)的问题,例如: java中的当前时间(以微秒为单位) 或 以小时,分钟,秒,毫秒,微秒获取时间

java format timestamp date

31
推荐指数
2
解决办法
10万
查看次数

SimpleDateFormat 宽大处理会导致意外行为

我发现 的SimpleDateFormat::parse(String source)行为(不幸的是)默认设置为 lenient: setLenient(true)。

默认情况下,解析是宽松的:如果输入不是该对象的 format 方法使用的形式,但仍然可以解析为日期,则解析成功。

如果我将宽大程度设置为false,则文档表示,通过严格解析,输入必须与该对象的格式匹配。我在没有宽松模式的情况下使用了 paring SimpleDateFormat,并且错误地在日期中出现了拼写错误(字母o而不是数字0)。(这是简短的工作代码:)

// PASSED (year 199)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
System.out.println(simpleDateFormat.parse("03.12.199o"));
simpleDateFormat.setLenient(false);
System.out.println(simpleDateFormat.parse("03.12.199o"));        //WTF?
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,这已经过去了,并且没有ParseException被抛出。我想更进一步:

// PASSED (year 1990)
String string = "just a String to mess with SimpleDateFormat";

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
System.out.println(simpleDateFormat.parse("03.12.1990" + string));
simpleDateFormat.setLenient(false);
System.out.println(simpleDateFormat.parse("03.12.1990" + string));
Run Code Online (Sandbox Code Playgroud)

我们继续:

// FAILED on the 2nd line
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
System.out.println(simpleDateFormat.parse("o3.12.1990"));
simpleDateFormat.setLenient(false);
System.out.println(simpleDateFormat.parse("o3.12.1990"));
Run Code Online (Sandbox Code Playgroud)

最后抛出异常:Unparseable …

java parsing date string-formatting simpledateformat

5
推荐指数
1
解决办法
1902
查看次数