你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
本文介绍在 Azure 资源管理器模板(ARM 模板)中使用日期的函数。
小窍门
              建议使用 Bicep ,因为它提供与 ARM 模板相同的功能,并且语法更易于使用。 若要了解详细信息,请参阅 date 函数。
dateTimeAdd
dateTimeAdd(base, duration, [format])
将持续时间添加到基值。 需要 ISO 8601 格式。
在 Bicep 中,使用函数 dateTimeAdd 。
参数
| 参数 | 必选 | 类型 | DESCRIPTION | 
|---|---|---|---|
| 基础映像 | 是的 | 字符串 | 添加的起始日期/时间值。 使用 ISO 8601 时间戳格式。 | 
| 持续时间 | 是的 | 字符串 | 要添加到基数的时间值。 它可以是负值。 使用 ISO 8601 持续时间格式。 | 
| 格式 | 否 | 字符串 | 日期时间结果的输出格式。 如果未提供,则使用基值的格式。 使用 标准格式 或 自定义格式 字符串。 | 
返回值
将持续时间值添加到基值的日期/时间值。
注解
该 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 年视为非跃升年,将一年加到一年的结果为 2024-01-01T00:00:00Z。 相反,在 2024 年的开始日期中添加一年,即跃年,结果为 2024-12-31T00:00:00Z,而不是 2025-01-01T00:00:00Z,因为一个跃年包括 366 天而不是 365 天。 此外,在 2 月的第一天增加一个月时,跳跃和非跨越年份之间的区别变得明显,导致月结果不同。
例子
以下示例模板显示了添加时间值的不同方法:
{
  "$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 | 字符串 | 2023/4/7 下午 2:53:14 | 
| subtract9DaysOutput | 字符串 | 2020/3/29 下午 2:53:14 | 
| add1HourOutput | 字符串 | 2020/4/7 下午 3:53:14 | 
下一个示例模板演示如何设置自动化计划的开始时间:
{
  "$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)
将纪元时间整数值转换为 ISO 8601 日期/时间。
在 Bicep 中,使用函数 dateTimeFromEpoch 。
参数
| 参数 | 必选 | 类型 | DESCRIPTION | 
|---|---|---|---|
| epochTime | 是的 | 整数 (int) | 要转换为日期/时间字符串的纪元时间。 | 
返回值
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 | 字符串 | 2023-05-02T15:16:13Z | 
| epochValue | int (整数) | 1683040573 | 
dateTimeToEpoch
dateTimeToEpoch(dateTime)
将 ISO 8601 日期/时间字符串转换为纪元时间整数值。
在 Bicep 中,使用函数 dateTimeToEpoch 。
参数
| 参数 | 必选 | 类型 | DESCRIPTION | 
|---|---|---|---|
| dateTime | 是的 | 字符串 | 要转换为纪元时间的日期/时间字符串。 | 
返回值
一个整数,表示 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 | 字符串 | 2023-05-02T15:16:13Z | 
| epochValue | int (整数) | 1683040573 | 
下一个示例使用纪元时间值设置密钥保管库中的密钥的过期时间:
{
  "$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 。
参数
| 参数 | 必选 | 类型 | DESCRIPTION | 
|---|---|---|---|
| 格式 | 否 | 字符串 | 要转换为字符串的 URI 编码值。 使用 标准格式 或 自定义格式字符串。 | 
注解
只能在表达式中对参数的默认值使用此函数。 在模板中的其他任何位置使用此函数都会返回错误。 不允许在模板的其他部分使用该函数,因为每次调用该函数,都会返回不同的值。 使用相同的参数部署同一模板不能可靠地生成相同的结果。
如果使用 此选项在 早期部署包含使用 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 | 字符串 | 20190305T175318Z | 
| utcShortOutput | 字符串 | 03/05/2019 | 
| utcCustomOutput | 字符串 | 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')]"
    }
  }
}
后续步骤
若要详细了解 ARM 模板中的部分,请参阅 ARM 模板的结构和语法。