Date functions for ARM templates

This article describes the functions for working with dates in your Azure Resource Manager template (ARM template).

Tip

We recommend Bicep because it offers the same capabilities as ARM templates and the syntax is easier to use. To learn more, see date functions.

dateTimeAdd

dateTimeAdd(base, duration, [format])

Adds a time duration to a base value. ISO 8601 format is expected.

In Bicep, use the dateTimeAdd function.

Parameters

Parameter Required Type Description
base Yes string The starting datetime value for the addition. Use ISO 8601 timestamp format.
duration Yes string The time value to add to the base. It can be a negative value. Use ISO 8601 duration format.
format No string The output format for the date time result. If not provided, the format of the base value is used. Use either standard format strings or custom format strings.

Return value

The datetime value that results from adding the duration value to the base value.

Remarks

The dateTimeAdd function doesn't take leap years into consideration, and P1Y should be interpreted as P365D, while P1M should be interpreted as P30D. The following json shows some examples:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "resources": [],
  "outputs": {
    "addOneYearNonLeap": {
      "type": "string",
      "value": "[dateTimeAdd('2023-01-01 00:00:00Z', 'P1Y')]"  //2024-01-01T00:00:00Z
    },
    "addOneYearLeap": {
      "type": "string",
      "value": "[dateTimeAdd('2024-01-01 00:00:00Z', 'P1Y')]"  //2024-12-31T00:00:00Z
    },
    "addOneMonthNonLeap": {
      "type": "string",
      "value": "[dateTimeAdd('2023-02-01 00:00:00Z', 'P1M')]"  //2023-03-03T00:00:00Z
    },
    "addOneMonthLeap": {
      "type": "string",
      "value": "[dateTimeAdd('2024-02-01 00:00:00Z', 'P1M')]"  //2024-03-02T00:00:00Z
    }
  }
}

In the preceding example, considering 2023 as a non-leap year, the outcome of adding one year to the initial day of the year is 2024-01-01T00:00:00Z. Conversely, adding one year to the starting day of 2024, a leap year, results in 2024-12-31T00:00:00Z, not 2025-01-01T00:00:00Z, given that a leap year comprises 366 days instead of 365 days. Furthermore, the distinction between leap and non-leap years becomes apparent when adding one month to the first day of February, leading to varying day-of-the-month results.

Examples

The following example template shows different ways of adding time values.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "baseTime": {
      "type": "string",
      "defaultValue": "[utcNow('u')]"
    }
  },
  "variables": {
    "add3Years": "[dateTimeAdd(parameters('baseTime'), 'P3Y')]",
    "subtract9Days": "[dateTimeAdd(parameters('baseTime'), '-P9D')]",
    "add1Hour": "[dateTimeAdd(parameters('baseTime'), 'PT1H')]"
  },
  "resources": [],
  "outputs": {
    "add3YearsOutput": {
      "value": "[variables('add3Years')]",
      "type": "string"
    },
    "subtract9DaysOutput": {
      "value": "[variables('subtract9Days')]",
      "type": "string"
    },
    "add1HourOutput": {
      "value": "[variables('add1Hour')]",
      "type": "string"
    }
  }
}

When the preceding template is deployed with a base time of 2020-04-07 14:53:14Z, the output is:

Name Type Value
add3YearsOutput String 4/7/2023 2:53:14 PM
subtract9DaysOutput String 3/29/2020 2:53:14 PM
add1HourOutput String 4/7/2020 3:53:14 PM

The next example template shows how to set the start time for an Automation schedule.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "omsAutomationAccountName": {
      "type": "string",
      "defaultValue": "demoAutomation",
      "metadata": {
        "description": "Use an existing Automation account."
      }
    },
    "scheduleName": {
      "type": "string",
      "defaultValue": "demoSchedule1",
      "metadata": {
        "description": "Name of the new schedule."
      }
    },
    "baseTime": {
      "type": "string",
      "defaultValue": "[utcNow('u')]",
      "metadata": {
        "description": "Schedule will start one hour from this time."
      }
    }
  },
  "variables": {
    "startTime": "[dateTimeAdd(parameters('baseTime'), 'PT1H')]"
  },
  "resources": [
    ...
    {
      "type": "Microsoft.Automation/automationAccounts/schedules",
      "apiVersion": "2022-08-08",
      "name": "[concat(parameters('omsAutomationAccountName'), '/', parameters('scheduleName'))]",

      "properties": {
        "description": "Demo Scheduler",
        "startTime": "[variables('startTime')]",
        "interval": 1,
        "frequency": "Hour"
      }
    }
  ],
  "outputs": {
  }
}

dateTimeFromEpoch

dateTimeFromEpoch(epochTime)

Converts an epoch time integer value to an ISO 8601 datetime.

In Bicep, use the dateTimeFromEpoch function.

Parameters

Parameter Required Type Description
epochTime Yes int The epoch time to convert to a datetime string.

Return value

An ISO 8601 datetime string.

Example

The following example shows output values for the epoch time functions.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "convertedEpoch": {
      "type": "int",
      "defaultValue": "[dateTimeToEpoch(dateTimeAdd(utcNow(), 'P1Y'))]"
    }
  },
  "variables": {
    "convertedDatetime": "[dateTimeFromEpoch(parameters('convertedEpoch'))]"
  },
  "resources": [],
  "outputs": {
    "epochValue": {
      "type": "int",
      "value": "[parameters('convertedEpoch')]"
    },
    "datetimeValue": {
      "type": "string",
      "value": "[variables('convertedDatetime')]"
    }
  }
}

The output is:

Name Type Value
datetimeValue String 2023-05-02T15:16:13Z
epochValue Int 1683040573

dateTimeToEpoch

dateTimeToEpoch(dateTime)

Converts an ISO 8601 datetime string to an epoch time integer value.

In Bicep, use the dateTimeToEpoch function.

Parameters

Parameter Required Type Description
dateTime Yes string The datetime string to convert to an epoch time.

Return value

An integer that represents the number of seconds from midnight on January 1, 1970.

Examples

The following example shows output values for the epoch time functions.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "convertedEpoch": {
      "type": "int",
      "defaultValue": "[dateTimeToEpoch(dateTimeAdd(utcNow(), 'P1Y'))]"
    }
  },
  "variables": {
    "convertedDatetime": "[dateTimeFromEpoch(parameters('convertedEpoch'))]"
  },
  "resources": [],
  "outputs": {
    "epochValue": {
      "type": "int",
      "value": "[parameters('convertedEpoch')]"
    },
    "datetimeValue": {
      "type": "string",
      "value": "[variables('convertedDatetime')]"
    }
  }
}

The output is:

Name Type Value
datetimeValue String 2023-05-02T15:16:13Z
epochValue Int 1683040573

The next example uses the epoch time value to set the expiration for a key in a key vault.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.5.6.12127",
      "templateHash": "16023511331197397029"
    }
  },
  "parameters": {
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "The location into which the resources should be deployed."
      }
    },
    "tenantId": {
      "type": "string",
      "defaultValue": "[subscription().tenantId]",
      "metadata": {
        "description": "The Tenant Id that should be used throughout the deployment."
      }
    },
    "userAssignedIdentityName": {
      "type": "string",
      "metadata": {
        "description": "The name of the existing User Assigned Identity."
      }
    },
    "userAssignedIdentityResourceGroupName": {
      "type": "string",
      "metadata": {
        "description": "The name of the resource group for the User Assigned Identity."
      }
    },
    "keyVaultName": {
      "type": "string",
      "defaultValue": "[format('vault-{0}', uniqueString(resourceGroup().id))]",
      "metadata": {
        "description": "The name of the Key Vault."
      }
    },
    "keyVaultKeyName": {
      "type": "string",
      "defaultValue": "cmkey",
      "metadata": {
        "description": "Name of the key in the Key Vault"
      }
    },
    "keyExpiration": {
      "type": "int",
      "defaultValue": "[dateTimeToEpoch(dateTimeAdd(utcNow(), 'P1Y'))]",
      "metadata": {
        "description": "Expiration time of the key"
      }
    },
    "storageAccountName": {
      "type": "string",
      "defaultValue": "[format('storage{0}', uniqueString(resourceGroup().id))]",
      "metadata": {
        "description": "The name of the Storage Account"
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.KeyVault/vaults",
      "apiVersion": "2021-10-01",
      "name": "[parameters('keyVaultName')]",
      "location": "[parameters('location')]",
      "properties": {
        "sku": {
          "name": "standard",
          "family": "A"
        },
        "enableSoftDelete": true,
        "enablePurgeProtection": true,
        "enabledForDiskEncryption": true,
        "tenantId": "[parameters('tenantId')]",
        "accessPolicies": [
          {
            "tenantId": "[parameters('tenantId')]",
            "permissions": {
              "keys": [
                "unwrapKey",
                "wrapKey",
                "get"
              ]
            },
            "objectId": "[reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('userAssignedIdentityResourceGroupName')), 'Microsoft.ManagedIdentity/userAssignedIdentities', parameters('userAssignedIdentityName')), '2018-11-30').principalId]"
          }
        ]
      }
    },
    {
      "type": "Microsoft.KeyVault/vaults/keys",
      "apiVersion": "2021-10-01",
      "name": "[format('{0}/{1}', parameters('keyVaultName'), parameters('keyVaultKeyName'))]",
      "properties": {
        "attributes": {
          "enabled": true,
          "exp": "[parameters('keyExpiration')]"
        },
        "keySize": 4096,
        "kty": "RSA"
      },
      "dependsOn": [
        "[resourceId('Microsoft.KeyVault/vaults', parameters('keyVaultName'))]"
      ]
    },
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2021-04-01",
      "name": "[parameters('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2",
      "identity": {
        "type": "UserAssigned",
        "userAssignedIdentities": {
          "[format('{0}', extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('userAssignedIdentityResourceGroupName')), 'Microsoft.ManagedIdentity/userAssignedIdentities', parameters('userAssignedIdentityName')))]": {}
        }
      },
      "properties": {
        "accessTier": "Hot",
        "supportsHttpsTrafficOnly": true,
        "minimumTlsVersion": "TLS1_2",
        "encryption": {
          "identity": {
            "userAssignedIdentity": "[extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('userAssignedIdentityResourceGroupName')), 'Microsoft.ManagedIdentity/userAssignedIdentities', parameters('userAssignedIdentityName'))]"
          },
          "services": {
            "blob": {
              "enabled": true
            }
          },
          "keySource": "Microsoft.Keyvault",
          "keyvaultproperties": {
            "keyname": "[parameters('keyVaultKeyName')]",
            "keyvaulturi": "[if(endsWith(reference(resourceId('Microsoft.KeyVault/vaults', parameters('keyVaultName'))).vaultUri, '/'), substring(reference(resourceId('Microsoft.KeyVault/vaults', parameters('keyVaultName'))).vaultUri, 0, sub(length(reference(resourceId('Microsoft.KeyVault/vaults', parameters('keyVaultName'))).vaultUri), 1)), reference(resourceId('Microsoft.KeyVault/vaults', parameters('keyVaultName'))).vaultUri)]"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.KeyVault/vaults', parameters('keyVaultName'))]",
        "[resourceId('Microsoft.KeyVault/vaults/keys', parameters('keyVaultName'), parameters('keyVaultKeyName'))]"
      ]
    }
  ]
}

utcNow

utcNow(format)

Returns the current (UTC) datetime value in the specified format. If no format is provided, the ISO 8601 (yyyyMMddTHHmmssZ) format is used. This function can only be used in the default value for a parameter.

In Bicep, use the utcNow function.

Parameters

Parameter Required Type Description
format No string The URI encoded value to convert to a string. Use either standard format strings or custom format strings.

Remarks

You can only use this function within an expression for the default value of a parameter. Using this function anywhere else in a template returns an error. The function isn't allowed in other parts of the template because it returns a different value each time it's called. Deploying the same template with the same parameters wouldn't reliably produce the same results.

If you use the option to rollback on error to an earlier successful deployment, and the earlier deployment includes a parameter that uses utcNow, the parameter isn't reevaluated. Instead, the parameter value from the earlier deployment is automatically reused in the rollback deployment.

Be careful redeploying a template that relies on the utcNow function for a default value. When you redeploy and don't provide a value for the parameter, the function is reevaluated. If you want to update an existing resource rather than create a new one, pass in the parameter value from the earlier deployment.

Return value

The current UTC datetime value.

Examples

The following example template shows different formats for the datetime value.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "utcValue": {
      "type": "string",
      "defaultValue": "[utcNow()]"
    },
    "utcShortValue": {
      "type": "string",
      "defaultValue": "[utcNow('d')]"
    },
    "utcCustomValue": {
      "type": "string",
      "defaultValue": "[utcNow('M d')]"
    }
  },
  "resources": [
  ],
  "outputs": {
    "utcOutput": {
      "type": "string",
      "value": "[parameters('utcValue')]"
    },
    "utcShortOutput": {
      "type": "string",
      "value": "[parameters('utcShortValue')]"
    },
    "utcCustomOutput": {
      "type": "string",
      "value": "[parameters('utcCustomValue')]"
    }
  }
}

The output from the preceding example varies for each deployment but will be similar to:

Name Type Value
utcOutput string 20190305T175318Z
utcShortOutput string 03/05/2019
utcCustomOutput string 3 5

The next example shows how to use a value from the function when setting a tag value.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "utcShort": {
      "type": "string",
      "defaultValue": "[utcNow('d')]"
    },
    "rgName": {
      "type": "string"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Resources/resourceGroups",
      "apiVersion": "2021-04-01",
      "name": "[parameters('rgName')]",
      "location": "chinanorth",
      "tags": {
        "createdDate": "[parameters('utcShort')]"
      },
      "properties": {}
    }
  ],
  "outputs": {
    "utcShortOutput": {
      "type": "string",
      "value": "[parameters('utcShort')]"
    }
  }
}

Next steps