Calculate the Difference Between Two Dates - malikovalibek/groovyForJira GitHub Wiki

Overview Calculate the difference in a time unit between two custom date fields. Save time manually tracking dates using this script.

Example As a project manager, I have an impending project deadline coming up. I need to see how long the tasks have been running to ensure my team is on track to complete the project on time. Using this script, I can configure a Scripted Field, or use the Script Console, to show me the time elapsed for each outstanding issue.

Good to Know Change the ChronoUnit value to calculate the difference in the time unit of your choice. You can check the documentation to see the available time units. The ChronoUnit#between method doesn't take into account fractional results, it rounds the result to the greatest integer less than or equal to the resulting value (floor function). (Server) Configure an Scripted field to check the information at a glance. (Cloud) Execute the script in the Script Console. import com.atlassian.jira.component.ComponentAccessor

import java.sql.Timestamp import java.time.temporal.ChronoUnit

// Get the required component def customFieldManager = ComponentAccessor.customFieldManager

// The name of the lower date custom field final String lowerDateCustomFieldName = "Lower Date Custom Field" // The name of the higher date custom field final String higherDateCustomFieldName = "Higher Date Custom Field"

// Get the custom field objects def lowerDateCustomField = customFieldManager.getCustomFieldObjects(issue).find { it.name == lowerDateCustomFieldName } def higherDateCustomField = customFieldManager.getCustomFieldObjects(issue).find { it.name == higherDateCustomFieldName } if (!lowerDateCustomField || !higherDateCustomField) { log.info "Could not find one ore more of the provided custom fields" return null }

// Get the date values from both issues def lowerDateValue = issue.getCustomFieldValue(lowerDateCustomField) as Timestamp def higherDateValue = issue.getCustomFieldValue(higherDateCustomField) as Timestamp // Transform both values to instants def lowerDateInstant = lowerDateValue?.toInstant() def higherDateInstant = higherDateValue?.toInstant()

// Change the chrono unit to obtain the difference in other time unit. final chronoUnit = ChronoUnit.DAYS // Calculate the difference between the lower and the higher date. lowerDateInstant && higherDateInstant ? chronoUnit.between(lowerDateInstant, higherDateInstant) : null