我们有一些时间戳表示为自纪元以来的毫秒。在用于记录,异常或toString()
方法的字符串中,需要格式化这些时间戳。简单而干净的格式就足够了。
那么,在Java中格式化时间戳的最简单,最快的方法是什么?
要求:
特别是,有人做过可用于此的JDK方法基准吗?
实际上我不想使用SimpleDateFormat,因为我认为它的灵活性带来了太多的开销。
答案 0 :(得分:1)
Apache Commons Lang的FastDateFormat
类绝对是SimpleDateFormat
的替代品。它速度快且线程安全(在多线程服务器环境中尤其有用)。所有模式都与SimpleDateFormat
兼容(时区和年份模式除外)。
构造函数的摘要是:
FastDateFormat(String pattern, TimeZone timeZone, Locale locale)
您可以在 FastDateFormat
找到更多信息答案 1 :(得分:1)
最快的实施很可能是:
Long.toString(millis);
如果表现是最重要的,你应该使用它。
实际上我不想使用SimpleDateFormat,因为我认为它的灵活性带来了太多的开销。
根据快速jmh基准测试,在我的笔记本电脑上,Long.toString
获得了1,200万次操作/秒,SimpleDateFormat
为200万次。
您的预算是多少?一旦你知道你能够决定哪一个是最合适的。
答案 2 :(得分:0)
尝试:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);
或者:
Date date = new Date(milliseconds);
不确定哪一个更快。
要将Date格式化为字符串,可以使用SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss.SSS"); // should output something like you desired: 20141220 174522.23
String formattedDate = sdf.format(date);
答案 3 :(得分:0)
易于使用且合理快速:
// All Java versions:
new java.sql.Timestamp(millis).toString(); // 2016-10-29 12:28:41.979
// Recommended when using Java 8+ (about +50% faster than Timestamp), standards compliant format
// checked with jmh 1.15
java.time.Instant.ofEpochMilli(millis).toString(); // 2016-10-29T10:28:41.979Z