Search code examples
datetimejasper-reports

How to get default value expression for java.sql.Timestamp in input control


I need to put default value expression for my datetime input control and it using class = java.sql.Timestamp

If using java.util.Date it can easily be done like so DATE(2019,8,28) but it only returns date.

How can to represent default value expression to have date and time using the class = java.sql.Timestamp so that it has the date and time?

It should show the correct date and time on the default input control when the report is executed.


Solution

  • You use new java.sql.Timestamp(long time), since the constructor Timestamp(int year,int month,int date,int hour,int minute,int second,int nano) is deprecated

    In your case if you only like to use the DATE function (no time) of jasper-reports the expression would be

    new java.sql.Timestamp(DATE(2019,8,28).getTime())
    

    the getTime() returns the milliseconds since January 1, 1970, 00:00:00 GMT needed in constructor

    If you also need to specify time jasper-reports have no function and I would use Java 8 (see below), however if this is not possibile you can use Timestamp.valueOf but you need to conform to format yyyy-[m]m-[d]d hh:mm:ss[.f...]

    java.sql.Timestamp.valueOf("2019-01-31 14:12:01")
    

    If you have other format you can for example parse your values.

    new java.sql.Timestamp(new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm").parse("2019/08/29 12:13").getTime()) 
    

    Java 8

    If you like to use the java.time package that was introduced in java 8 (it's thread safe, handles more clearly time zones etc) a similar expression can be used.

    new java.sql.Timestamp(java.time.LocalDate.of(2019, 08, 28).atTime(0,0).atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli())
    

    or if you like to specify time directly in constructor use the LocaDateTime.of

    new java.sql.Timestamp(java.time.LocalDateTime.of(2015, 02, 20, 12, 40, 25).atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli())
    

    To understand more see the java.time api