Example scripts
To homepage
Jira

Calculate the Difference Between Two Dates
Created 7 month(s) ago, Updated 21 day(s) ago
App in script

ScriptRunner For Jira
by Adaptavist
Compatibility

Jira
Language |
groovy
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
// The issue key
final issueKey = '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 issueFieldId = getFieldIdFromName(dateFieldName)
// Pick a date from another date field, in this case the built-in 'Updated' field
def updatedFieldId = 'updated'
def createdDate = ZonedDateTime.parse(getIssueField(issueKey, issueFieldId), formatter)
def updatedDate = ZonedDateTime.parse(getIssueField(issueKey, updatedFieldId), formatter)
def dateDifference = chronoUnit.between(createdDate, updatedDate)
/**
* Get the issue field data on a given issue
* @param issueKey The key of the issue to get the data from
* @param fieldId The field to get the data of
* @return The value of the field
*/
String getIssueField(issueKey, fieldId) {
def issueFieldValue = null
def result = get('/rest/api/2/issue/' + issueKey)
.header('Content-Type', 'application/json')
.asObject(Map)
if (result.status == 200) {
result.body.fields.each { key, value ->
if (key == fieldId) {
issueFieldValue = value.toString()
}
}
logger.warn "${issueFieldValue}"
return issueFieldValue
}
logger.warn "Failed to find issue: 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