gpt4 book ai didi

Java SimpleDateFormat 添加随机零

转载 作者:行者123 更新时间:2023-11-30 10:46:21 25 4
gpt4 key购买 nike

我有一个 Android 应用程序,它每秒输出数百行的 csv。每行都有一个时间戳,基本上是这样生成的:

String formatTimeStamp (Calendar cal)
{
SimpleDateFormat timeFormatISO = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
return timeFormatISO.format(cal.getTime());
}

一些时间戳(可能是千分之一)中有意外的零,看起来像这样:

2016-04-12T09:0011:30

2016-04-12T0009:0011:30

2016-04-0012T09:11:30

事件似乎完全是任意的,至少我看不到它们背后的任何模式。有时两行错误之间有几千行,有时只有一行。

日期格式只在代码中的一处定义。

编辑:

Here

是我上次运行的错误时间戳,您可以看一下。关于它们,我唯一注意到的是它总是在日期元素前面有两个前导零,但从不在年份前面。

编辑 2:

问题已解决!结果证明 SimpleDateFormat 不是线程安全的,如果使用不当,它会对字符串做一些奇怪的事情。我不知道多线程会是一个问题,所以我没有在最初的问题中指出。抱歉造成混淆。

最佳答案

"Turns out SimpleDateFormat is not thread safe and does weird things to strings if used incorrectly."

您在问题中向我们展示的代码是线程安全的,除非以非安全方式处理 cal 的值。

SimpleDateFormat 实例是线程限制的;即没有其他线程可以看到它。因此,它的线程安全性或其他方面是不相关的。

我的猜测是,在您的实际代码中,您有多个线程试图共享一个 SimpleDateFormat 实例。 javadoc 说:

"It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."

关于Java SimpleDateFormat 添加随机零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36573275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com