Skip to main content
Book your demo
Example scripts
To homepage
Jira
Cloud icon
Cloud

Calculate the Difference Between Two Dates

Created 1 year ago, Updated 0 day(s) ago
App in script
ScriptRunner For Jira
ScriptRunner For Jira
by Adaptavist
Compatibility
compatibility bullet
Jira
Language |
groovy
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

// The work item key
final workItemKey = 'TEST-1'
final dateFieldName = 'Created'
final chronoUnit = ChronoUnit.DAYS

// Jira datetime field format
def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")

// Pick a date that you would like to calculate from
def workItemFieldId = getFieldIdFromName(dateFieldName)
// Pick a date from another date field, in this case the built-in 'Updated' field
def updatedFieldId = 'updated'

def createdDate = ZonedDateTime.parse(getWorkItemField(workItemKey, workItemFieldId), formatter)
def updatedDate = ZonedDateTime.parse(getWorkItemField(workItemKey, updatedFieldId), formatter)

def dateDifference = chronoUnit.between(createdDate, updatedDate)

/**
 * Get the work item field data on a given work item
 * @param workItemKey The key of the work item to get the data from
 * @param fieldId The field to get the data of
 * @return The value of the field
 */
String getWorkItemField(workItemKey, fieldId) {
    def workItemFieldValue = null
    def result = get('/rest/api/2/issue/' + workItemKey)
        .header('Content-Type', 'application/json')
        .asObject(Map)
    if (result.status == 200) {
        result.body.fields.each { key, value ->
            if (key == fieldId) {
                workItemFieldValue = value.toString()
            }
        }
        logger.warn "${workItemFieldValue}"
        return workItemFieldValue
    }

    logger.warn "Failed to find work item: Status: ${result.status} ${result.body}"
    null
}

/**
 * Get the id of a field
 * @param fieldName The name of the field
 * @return The field id
 */
String getFieldIdFromName(String fieldName) {
    def fields = get("/rest/api/2/field").asObject(List).body
    def customFieldObject = (fields as List<Map>).find { Map field ->
        field.name == fieldName
    }
    (customFieldObject as Map).id
}

// Return the value
"${dateDifference} ${chronoUnit.toString().toLowerCase()}"

Having an issue with this script?
Report it here