【问题标题】:Cannot invoke format(Date) on the primitive type void无法在原始类型 void 上调用格式(日期)
【发布时间】:2017-03-29 20:30:31
【问题描述】:

在碧玉报告中我正在尝试以下内容

new SimpleDateFormat("dd.MM.yyyy HH:mm").setTimeZone(TimeZone.getTimeZone("UTC")).format( new Date(1483337940000L));

在文本字段表达式中。

但我得到了错误

无法在原始类型 void 上调用格式(日期)

是不是和java下面的代码一样?

1483337940000L is 02.01.2107 07:19

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String test  = sdf.format(new Date(1483337940000L)); // Here I am getting 06:19

String test2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").setTimeZone(TimeZone.getTimeZone("UTC")).format( new Date(1483337940000L)); // Here I am getting the error Cannot invoke format(Date) on the primitive type void

【问题讨论】:

  • setTimeZone 不返回值。这是一个无效的方法
  • 成语obj.operation1().operation2().operation3() 仅在每个操作都定义为返回调用它的对象时才有效。这不是该操作的定义方式,因此您不能使用这种“链式命令”习语。
  • 我想这里不会发生其他事情;所以请考虑在某个时候接受 ;-)

标签: java


【解决方案1】:

方法setTimeZone()来自DateFormat类;并且不返回值;因为它是void

当你写作时

sdf.setTimeZone(TimeZone.getTimeZone("UTC")).format(new Date(1483337940000L)); 

您尝试在 setTimeZone() 的结果上调用 format()

但是由于该方法没有结果;那一定会失败!

真正的要点是:不要假设方法在做什么。是的,一些 API 被编写为允许“流畅调用”,通过返回调用方法的对象;但不是全部!所以,当有疑问时:检查 javadoc。首先。

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 2013-11-11
    • 2018-11-03
    • 2012-04-15
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多