在不创建大量对象的情况下将yyyy-MM-dd格式的java.util.Date转换为String [英] Convert java.util.Date to String in yyyy-MM-dd format without creating a lot of objects

查看:99
本文介绍了在不创建大量对象的情况下将yyyy-MM-dd格式的java.util.Date转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要大量地将java.util.Date转换为yyyy-MM-dd格式的String.

I need to convert java.util.Date to String in yyyy-MM-dd format in a big amounts.

我刚刚移到Java 8,想知道如何正确地做它. 我使用Java 7的解决方案是:

I have just moved to java 8 and want to know how to do it properly. My solution with Java 7 was like:

DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN)

DATE_FORMATTER.print(value.getTime())

这有助于我避免创建很多冗余对象.

It helped me not to create a lots of redundant objects.

所以现在当我移到Java 8时,我想正确地重写它,但是:

So now when I moved to java 8 I want rewrite it properly but:

LocalDate.fromDateFields(value).toString())

每次创建新的LocalDate对象都会创建一个新的对象,这会给GC带来很多工作.

creates each time new LocalDate object and this gives a lot of work to GC.

有什么办法可以解决我的问题? 性能和线程安全性非常重要.

Are there any ways to solve my problem? Performance and thread-safety are very important.

经过一些测试,我发现即使使用以下方法创建新对象,

After some testing I have found that even with creating new objects construction with:

new SimpleDateFormat("yyyy-MM-dd")).format(value)) 

这个主题上最快的.

推荐答案

以下仅是将旧的Date转换为新的LocalDate的开销.

The following only has an overhead for the conversion of the old Date to the new LocalDate.

    Date date = new Date();
    LocalDate ldate = LocalDate.from(date.toInstant().atZone(ZoneOffset.UTC));
    String s = DateTimeFormatter.ISO_DATE.format(ldate); // uuuu-MM-dd

但是,DateTimeFormatters是线程安全的,因此每次调用将有一个实例化.

It is true however that DateTimeFormatters are thread-safe and hence will have one instantiation more per call.

P.S.

由于报告了异常,我添加了.atZone(ZoneOffset.UTC),并且@Flown的解决方案是:指定区域.由于Date不一定用于UTC日期,因此一个人可以使用另一个.

I added .atZone(ZoneOffset.UTC) because of a reported exception, and @Flown's solution: specifying the zone. As Date is not necessarily used for UTC dates, one might use another one.

这篇关于在不创建大量对象的情况下将yyyy-MM-dd格式的java.util.Date转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆