【发布时间】:2020-09-02 17:27:10
【问题描述】:
我正在尝试使用 Gatling 和 scala 插件 (https://github.com/jeanadrien/gatling-mqtt-protocol) 做一个数据生成器。生成的数据包括日期。
这里是相关代码:
val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
format.setTimeZone(TimeZone.getTimeZone("UTC"));
val publish = repeat(repeatTimes) {
feed(feeder)
.exec(mqtt("publish")
.publish(format.format(Calendar.getInstance().getTime( )), QoS.AT_LEAST_ONCE, retain = false))
.pause(pauseTime)
}
我的问题是大约 90% 的生成日期都是这种格式:
2020-09-02T17:06:48Z
虽然大约 10% 的生成日期采用这种格式:
2020-09-02T17:06:48Z02:00
我只想要第一种格式。我尝试添加
format.setTimeZone(TimeZone.getTimeZone("UTC"));
当我第一次看到问题但没有效果时。
【问题讨论】:
-
我建议你不要使用
SimpleDateFormat和Calendar。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的OffsetDateTime和DateTimeFormatter。 -
将
Z硬编码为格式模式字符串中的文字是错误的。永远不要那样做。Z是与 UTC 的偏移量(零),必须格式化为偏移量,否则您很可能会得到不正确的结果。参见例如parsing date/time to localtimezone。
标签: scala date simpledateformat gatling