如何用模式格式化java.time.LocalDateTime和java.time.LocalDate?

时间:2016-08-08 13:38:15

标签: java jasper-reports java-time

在以下剪辑中,属性$F属于java.time.LocalDateTime类或java.time.LocalDate

<textField pattern="EE. dd.MM.yyyy">
    <reportElement...>
    </reportElement>
    <textFieldExpression><![CDATA[$F{theLocalDateTime}]]></textFieldExpression>
</textField>

如何在jasper报告中使用textField pattern格式化此属性?

2 个答案:

答案 0 :(得分:7)

要在日期/时间对象的当前版本的jasper-report中使用模式属性,您需要一个java.util.Date类或其中一个子类。

解决方案是转换java.time.LocalDatejava.time.LocalDateTime

转换为java.util.Date

from java.time.LocalDate

<textField pattern="EE. dd.MM.yyyy">
    <reportElement...>
    </reportElement>
    <textFieldExpression><![CDATA[java.util.Date.from($F{theLocalDate}.atStartOfDay(java.time.ZoneId.systemDefault()).toInstant())]]></textFieldExpression>
</textField>

from java.time.LocalDateTime

<textField pattern="EE. dd.MM.yyyy">
    <reportElement...>
    </reportElement>
    <textFieldExpression><![CDATA[java.util.Date.from($F{theLocalDateTime}.atZone(java.time.ZoneId.systemDefault()).toInstant())]]></textFieldExpression>
</textField>

Converting to java.sql.Timestamp

来自java.time.LocalDate

<textField pattern="EE. dd.MM.yyyy">
    <reportElement...>
    </reportElement>
    <textFieldExpression><![CDATA[java.sql.Timestamp.valueOf($F{theLocalDate}.atStartOfDay())]]></textFieldExpression>
</textField>
来自java.time.LocalDateTime

<textField pattern="EE. dd.MM.yyyy">
    <reportElement...>
    </reportElement>
    <textFieldExpression><![CDATA[java.sql.Timestamp.valueOf($F{theLocalDateTime})]]></textFieldExpression>
</textField>
  

注意:应用模式始终是首选解决方案,特别是在何时   导出到excel,因为正确的类将传递给poi(因此   excel会将列识别为日期并应用与中的格式相同的格式   图案)

答案 1 :(得分:0)

由于 java.time 模块有点复杂和冗长,我通常会创建一些变量来保存已编译的 DateTimeFormatter 以供进一步使用。

我希望我的报告适应任何语言环境,所以我不使用字符串文字进行格式化。

我正在使用报告区域设置,但您可以使用 java.util.Locale.forLanguageTag("en-US") 选择您的区域设置,例如。

如果需要,您也可以更改 java.time.format.FormatStyle

LocalDate 格式化程序:

    <variable name="dateFormatter" class="java.time.format.DateTimeFormatter">
        <variableExpression><![CDATA[java.time.format.DateTimeFormatter
  .ofLocalizedDate(java.time.format.FormatStyle.SHORT)
  .withLocale($P{REPORT_LOCALE})
  .withChronology(java.time.chrono.Chronology.ofLocale($P{REPORT_LOCALE}))]]></variableExpression>
    </variable>

LocalDateTime 格式化程序:

    <variable name="dateTimeFormatter" class="java.time.format.DateTimeFormatter">
        <variableExpression><![CDATA[java.time.format.DateTimeFormatter
  .ofLocalizedDateTime(java.time.format.FormatStyle.SHORT)
  .withLocale($P{REPORT_LOCALE})
  .withChronology(java.time.chrono.Chronology.ofLocale($P{REPORT_LOCALE}))]]></variableExpression>
    </variable>

现在我可以通过这种方式格式化 LocalDate 字段:

$F{localDateField}.format($V{dateFormatter})

这样的 LocalDateTime 字段:

$F{localDateTimeField}.format($V{dateTimeFormatter})