ARM 範本的日期函式

本文說明用來在 Azure Resource Manager 範本 (ARM 範本) 中處理日期的函式。

提示

我們建議使用 Bicep,因為其提供的功能與 ARM 範本相同,而且語法更易於使用。 若要深入了解,請參閱日期函式。

dateTimeAdd

dateTimeAdd(base, duration, [format])

將持續時間加至基底值。 需使用 ISO 8601 格式。

在 Bicep 中,使用 dateTimeAdd 函式。

參數

參數 必要 類型​ 描述
base Yes string 要加上的開始日期時間值。 使用 ISO 8601 時間戳記格式
duration Yes string 要加至基底的時間值。 可以是負數值。 使用 ISO 8601 持續時間格式
format No string 日期時間結果的輸出格式。 如果未提供,則會使用基底值的格式。 使用標準格式字串自訂格式字串

傳回值

將持續時間值加至基底值所產生的日期時間值。

備註

dateTimeAdd 函式不考慮閏年,P1Y 應解譯為 P365D,而 P1M 應解譯為 P30D。 下列 JSON 提供了一些範例:

{
  "$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
    }
  }
}

在上述範例中,由於 2023 並非閏年,因此 2023 年第一日加一年的結果為 2024-01-01T00:00:00Z。 相反地,2024 年為閏年,一年有 366 天而非 365 天,因此第一日加一年的結果為 2024-12-31T00:00:00Z,而非 2025-01-01T00:00:00Z。 此外,在二月第一日增加一個月時,由於閏年與非閏年的差異,二月份的天數也會因此出現不同結果。

範例

下列範例範本顯示加上時間值的不同方式。

{
  "$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"
    }
  }
}

當前述範本使用 2020-04-07 14:53:14Z 的基底時間部署時,輸出為:

名稱 類型
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

下一個範例範本示範如何設定自動化排程的開始時間。

{
  "$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)

將 Epoch 時間整數值轉換為 ISO 8601 日期時間。

在 Bicep 中,使用 dateTimeFromEpoch 函式。

參數

參數 必要 類型​ 描述
epochTime Yes int 要轉換成日期時間字串的 Epoch 時間。

傳回值

ISO 8601 日期時間字串。

範例

下列範例顯示 Epoch 時間函式的輸出值。

{
  "$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')]"
    }
  }
}

輸出如下:

名稱 類型
datetimeValue String 2023-05-02T15:16:13Z
epochValue int 1683040573

dateTimeToEpoch

dateTimeToEpoch(dateTime)

將 ISO 8601 日期時間字串轉換為 Epoch 時間整數值。

在 Bicep 中,使用 dateTimeToEpoch 函式。

參數

參數 必要 類型​ 描述
dateTime Yes string 要轉換成 Epoch 時間的日期時間字串。

傳回值

表示 1970 年 1 月 1 日午夜秒數的整數。

範例

下列範例顯示 Epoch 時間函式的輸出值。

{
  "$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')]"
    }
  }
}

輸出如下:

名稱 類型
datetimeValue String 2023-05-02T15:16:13Z
epochValue int 1683040573

下一個範例會使用 epoch 時間值來設定金鑰保存庫中金鑰的到期日。

{
  "$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)

以指定的格式傳回目前的 (UTC) 日期時間值。 如果未提供格式,則會使用 ISO 8601 (yyyyMMddTHHmmssZ) 格式。 此函式只能用於參數的預設值。

在 Bicep 中,使用 utcNow 函式。

參數

參數 必要 類型​ 描述
format No string 要轉換為字串的 URI 編碼值。 使用標準格式字串自訂格式字串

備註

您只能在運算式內使用此函式,以取得參數的預設值。 在 Bicep 檔案中的其他地方使用此函式會傳回錯誤。 在範本的其他部分不允許該函式,因為這會在每次呼叫時傳回不同的值。 使用相同的參數部署相同的範本,並不一定會產生相同的結果。

如果您使用發生錯誤時復原選項,以復原為先前的成功部署,而先前的部署包括使用 utcNow 的參數,則該參數並不會受到重新評估。 相反地,系統會在復原部署中自動重複使用來自稍早部署的參數值。

重新部署相依於 utcNow 函式以取得預設值的範本時,請謹慎小心。 當您重新部署且未提供參數的值時,系統會重新評估該函式。 如果您想更新現有的資源,而不是建立新的資源,請傳入來自先前部署的參數值。

傳回值

目前的 UTC 日期時間值。

範例

下列範例範本示範不同格式的日期時間值。

{
  "$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')]"
    }
  }
}

前述範例的輸出會隨著個別部署而有所不同,但會類似於:

名稱 類型
utcOutput string 20190305T175318Z
utcShortOutput string 03/05/2019
utcCustomOutput string 3 5

下個範例示範如何在設定標記值時使用來自函式的值。

{
  "$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": "westeurope",
      "tags": {
        "createdDate": "[parameters('utcShort')]"
      },
      "properties": {}
    }
  ],
  "outputs": {
    "utcShortOutput": {
      "type": "string",
      "value": "[parameters('utcShort')]"
    }
  }
}

下一步