FAQ: How can I handle dates when writing a Quantexa Score in Scala?
Handling Temporal Data
Temporal data refers to any data that is associated with a specific point or period in time. This includes the use of dates, times, intervals or timestamps.
This information is useful for indicating when an event has occurred.
LocalDate
One common way of handling temporal data such as dates in your score logic is by using the LocalDate option. This is part of the java.time package.
Using LocalDate allows you to manipulate dates, calculate differences between two dates, format dates into strings and parse strings into Date objects.
In Scala you can also use the java.time.format.DateTimeFormatter
class to format and parse temporal data into specific patterns.
Here is an example below:
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
The above line will help parse your dates into an appropriate format.
LocalDate.parse(yourDate, dateTimeFormatter)
The above line ensures that the date is parsed as a LocalDate object and would then look like this: "2024-04-17"
Now that we have our localDate we can now perform operations which can be useful when writing your score logic.
Commonly Used Operations
Comparing dates
yourDate.isAfter(anotherLocalDate)
yourDate.isBefore(anotherLocalDate)
yourDate.isEqual(anotherLocalDate)
Extracting the month, year and day
yourDate.getMonth()
yourDate.getYear()
yourDate.getDayOfMonth()
Calculating the period between two dates
To compare two LocalDates we can use the .between
method after having imported the java.time.Period
class.
We can implement the functionality seen above to extract the period and years in the following example:
val duration = Period.between(yourDate, anotherLocalDate)
duration.getYears()
FAQ: Type Mismatch Errors
A common issue experienced in the academy is a type mismatch error when using .addRelatedDate.
When using .addRelatedDate for the addition of a dynamic date field to your score, it is recommended that you use a Date type. LocalDate can still however be used within your comparison logic.