You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure DevOps YAML获取带月份缩写的当前日期报错问题

Azure DevOps YAML流水线生成带月份缩写的日期变量

Azure DevOps流水线表达式引擎的format函数不支持MMM这类月份缩写格式符,直接使用会触发The format specifiers 'MMM' are not valid for objects of type 'DateTime'错误。以下是两种可行的解决方法:

方法一:通过PowerShell任务生成变量

利用PowerShell的日期格式化能力生成带月份缩写的日期,再将其设置为流水线全局变量:

variables:
  executionTitle: "My Test Execution $(currentDate)"

steps:
- powershell: |
    # 生成格式为yyyy.MMM.dd的日期字符串
    $currentDate = Get-Date -Format "yyyy.MMM.dd"
    # 将变量设为流水线可用
    Write-Host "##vso[task.setvariable variable=currentDate;]$currentDate"
  displayName: '生成带月份缩写的日期变量'

# 验证变量示例
- script: |
    echo $(executionTitle)
  displayName: '输出执行标题'

方法二:纯表达式映射月份缩写

通过流水线表达式手动映射月份数字与缩写,无需额外任务:

variables:
  # 映射月份数字到英文缩写
  monthAbbr: $[ 
    replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
      pipeline.startTime.month,
      1, 'Jan'),
      2, 'Feb'),
      3, 'Mar'),
      4, 'Apr'),
      5, 'May'),
      6, 'Jun'),
      7, 'Jul'),
      8, 'Aug'),
      9, 'Sep'),
      10, 'Oct'),
      11, 'Nov'),
      12, 'Dec')
    ]
  # 拼接日期字符串
  currentDate: $[ format('{0:yyyy}.{1}.{0:dd}', pipeline.startTime, variables.monthAbbr) ]
  executionTitle: "My Test Execution $(currentDate)"

steps:
- script: |
    echo $(executionTitle)
  displayName: '输出执行标题'

两种方案对比:

  • 方法一简洁易维护,支持系统默认的月份缩写规则,推荐使用。
  • 方法二无需额外任务步骤,但需要手动维护月份映射逻辑,适合必须在变量阶段定义的场景。

内容的提问来源于stack exchange,提问作者AndreiB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:52:15